Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * Copyright (c) 2021 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/*/task never contains "0".
0017 #include <sys/types.h>
0018 #include <dirent.h>
0019 #include <signal.h>
0020 #include <stdio.h>
0021 #include <stdlib.h>
0022 #include <string.h>
0023 #include <unistd.h>
0024 #include <pthread.h>
0025 
0026 static pid_t pid = -1;
0027 
0028 static void atexit_hook(void)
0029 {
0030     if (pid > 0) {
0031         kill(pid, SIGKILL);
0032     }
0033 }
0034 
0035 static void *f(void *_)
0036 {
0037     return NULL;
0038 }
0039 
0040 static void sigalrm(int _)
0041 {
0042     exit(0);
0043 }
0044 
0045 int main(void)
0046 {
0047     pid = fork();
0048     if (pid == 0) {
0049         /* child */
0050         while (1) {
0051             pthread_t pth;
0052             pthread_create(&pth, NULL, f, NULL);
0053             pthread_join(pth, NULL);
0054         }
0055     } else if (pid > 0) {
0056         /* parent */
0057         atexit(atexit_hook);
0058 
0059         char buf[64];
0060         snprintf(buf, sizeof(buf), "/proc/%u/task", pid);
0061 
0062         signal(SIGALRM, sigalrm);
0063         alarm(1);
0064 
0065         while (1) {
0066             DIR *d = opendir(buf);
0067             struct dirent *de;
0068             while ((de = readdir(d))) {
0069                 if (strcmp(de->d_name, "0") == 0) {
0070                     exit(1);
0071                 }
0072             }
0073             closedir(d);
0074         }
0075 
0076         return 0;
0077     } else {
0078         perror("fork");
0079         return 1;
0080     }
0081 }