| 1 |
#define _GNU_SOURCE |
| 2 |
#include <stdio.h> |
| 3 |
#include <signal.h> |
| 4 |
#include <unistd.h> |
| 5 |
#include <sys/mman.h> |
| 6 |
#include <fcntl.h> |
| 7 |
#include <sched.h> |
| 8 |
|
| 9 |
#define STKS (4*4096) |
| 10 |
|
| 11 |
#ifndef CLONE_NEWPID |
| 12 |
#define CLONE_NEWPID 0x20000000 |
| 13 |
#endif |
| 14 |
|
| 15 |
static int do_test(void *logf) |
| 16 |
{ |
| 17 |
int fd, i = 0; |
| 18 |
|
| 19 |
setsid(); |
| 20 |
|
| 21 |
close(0); |
| 22 |
close(1); |
| 23 |
close(2); |
| 24 |
|
| 25 |
fd = open("/dev/null", O_RDONLY); |
| 26 |
if (fd != 0) { |
| 27 |
dup2(fd, 0); |
| 28 |
close(fd); |
| 29 |
} |
| 30 |
|
| 31 |
fd = open(logf, O_WRONLY | O_TRUNC | O_CREAT, 0600); |
| 32 |
dup2(fd, 1); |
| 33 |
dup2(fd, 2); |
| 34 |
if (fd != 1 && fd != 2) |
| 35 |
close(fd); |
| 36 |
|
| 37 |
while (1) { |
| 38 |
sleep(1); |
| 39 |
printf("%d\n", i++); |
| 40 |
fflush(stdout); |
| 41 |
} |
| 42 |
|
| 43 |
return 0; |
| 44 |
} |
| 45 |
|
| 46 |
int main(int argc, char **argv) |
| 47 |
{ |
| 48 |
int pid; |
| 49 |
void *stk; |
| 50 |
|
| 51 |
stk = mmap(NULL, STKS, PROT_READ | PROT_WRITE, |
| 52 |
MAP_PRIVATE | MAP_ANON | MAP_GROWSDOWN, 0, 0); |
| 53 |
pid = clone(do_test, stk + STKS, SIGCHLD | CLONE_NEWPID, argv[1]); |
| 54 |
if (pid < 0) { |
| 55 |
fprintf(stderr, "clone() failed: %m\n"); |
| 56 |
return 1; |
| 57 |
} |
| 58 |
printf("%d\n", pid); |
| 59 |
|
| 60 |
return 0; |
| 61 |
} |