Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * Copyright © 2018 Alexey Dobriyan <adobriyan@gmail.com>
0003  *
0004  * Permission to use, copy, modify, and distribute this software for any
0005  * purpose with or without fee is hereby granted, provided that the above
0006  * copyright notice and this permission notice appear in all copies.
0007  *
0008  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
0009  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
0010  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
0011  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
0012  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
0013  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
0014  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
0015  */
0016 /* Test that /proc/loadavg correctly reports last pid in pid namespace. */
0017 #include <errno.h>
0018 #include <sched.h>
0019 #include <sys/types.h>
0020 #include <sys/stat.h>
0021 #include <fcntl.h>
0022 #include <unistd.h>
0023 #include <sys/wait.h>
0024 
0025 int main(void)
0026 {
0027     pid_t pid;
0028     int wstatus;
0029 
0030     if (unshare(CLONE_NEWPID) == -1) {
0031         if (errno == ENOSYS || errno == EPERM)
0032             return 4;
0033         return 1;
0034     }
0035 
0036     pid = fork();
0037     if (pid == -1)
0038         return 1;
0039     if (pid == 0) {
0040         char buf[128], *p;
0041         int fd;
0042         ssize_t rv;
0043 
0044         fd = open("/proc/loadavg" , O_RDONLY);
0045         if (fd == -1)
0046             return 1;
0047         rv = read(fd, buf, sizeof(buf));
0048         if (rv < 3)
0049             return 1;
0050         p = buf + rv;
0051 
0052         /* pid 1 */
0053         if (!(p[-3] == ' ' && p[-2] == '1' && p[-1] == '\n'))
0054             return 1;
0055 
0056         pid = fork();
0057         if (pid == -1)
0058             return 1;
0059         if (pid == 0)
0060             return 0;
0061         if (waitpid(pid, NULL, 0) == -1)
0062             return 1;
0063 
0064         lseek(fd, 0, SEEK_SET);
0065         rv = read(fd, buf, sizeof(buf));
0066         if (rv < 3)
0067             return 1;
0068         p = buf + rv;
0069 
0070         /* pid 2 */
0071         if (!(p[-3] == ' ' && p[-2] == '2' && p[-1] == '\n'))
0072             return 1;
0073 
0074         return 0;
0075     }
0076 
0077     if (waitpid(pid, &wstatus, 0) == -1)
0078         return 1;
0079     if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
0080         return 0;
0081     return 1;
0082 }