|
|
测试程序,展示一下 clone() 的灵活(灵活=强大)。clone 出来的子进程与父进程共享内存。父进程给变量 a 赋值:a = 1;子进程让变量 a 递增:++a;子进程打印出 a = 2。父进程也打印出 a = 2。这说明子进程更改了父进程中变量 a 的值——就是说,父子进程共用了同一个内存空间。注意 fork() 不可能做到这一点。
另外,父子进程之间所建立的管道,工作也正常。父进程把命令行参数作为字符串输出到管道。子进程从管道接收字符,并输出到控制台。
- /* pipe.c */
- #define _GNU_SOURCE
- #include <malloc.h>
- #include <signal.h>
- #include <sys/types.h>
- #include <syscall.h>
- #include <sched.h>
- #include <sys/wait.h>
- #include <sys/utsname.h>
- #include <sched.h>
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- int a;
- char buf;
- int pipefd[2];
- char stack[8192];
- int clone_func()
- {
- printf ("This is child, pid = %d, ppid = %d, a = %d\n", getpid(), getppid(), ++a);
- /* Child reads from pipe */
- close(pipefd[1]); /* Close unused write end */
- while (read(pipefd[0], &buf, 1) > 0)
- write(STDOUT_FILENO, &buf, 1);
- write(STDOUT_FILENO, "\n", 1);
- close(pipefd[0]);
- exit(EXIT_SUCCESS);
- }
- int
- main(int argc, char *argv[])
- {
- if (argc != 2) {
- fprintf(stderr, "Usage: %s <string>\n", argv[0]);
- exit(EXIT_FAILURE);
- }
- if (pipe(pipefd) == -1) {
- perror("pipe");
- exit(EXIT_FAILURE);
- }
- a = 1;
- printf ("Creating child ...\n");
- clone (&clone_func, stack + 8192, CLONE_VM, 0);
- /* Parent writes argv[1] to pipe */
- close(pipefd[0]); /* Close unused read end */
- write(pipefd[1], argv[1], strlen(argv[1]));
- close(pipefd[1]); /* Reader will see EOF */
- //wait(NULL); /* Wait for child */
- sleep (5);
- printf ("This is parent, pid = %d, ppid = %d, a = %d\n", getpid(), getppid(), a);
- return 0;
- }
复制代码
编译和运行结果如下:
user@ttyd:~$ gcc pipe.c
user@ttyd:~$ ./a.out ttttttttttttt
Creating child ...
This is child, pid = 1802, ppid = 1801, a = 2
ttttttttttttt
This is parent, pid = 1801, ppid = 1690, a = 2
user@ttyd:~$ |
|