|
管道的一种常见用法是:
在父进程创建子进程后向子进程传递参数。例如,一个应用软件有一个主进程和许多个不同的子进程。主进程创建子进程后,在子进程调用 exec 函数执行一个新程序前,通过管道给即将执行的程序传递命令行参数,子进程根据传来的参数进行初始化或其他操作。下面的程序包括一个主进程程序和一个子进程中要执行的程序。
主进程程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[], char **environ)
{
int fd[2];
pid_t pid;
int stat_val;
if (argc < 2) {
printf("wrong parameters \n");
exit(0);
}
if (pipe(fd)) {
perror("pipe failed");
exit(1);
}
pid = fork();
switch (pid) {
case -1:
perror("fork failed\n");
exit(1);
case 0:
close(0);
dup(fd[0]);
execve("ctrlprocess.exe", (void *)argv, environ);
exit(0);
default:
close(fd[0]);
write(fd[1], argv[1], strlen(argv[1]));
break;
}
wait(&stat_val);
exit(0);
} 要在子进程中执行的程序:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int arg, char *argv[])
{
char buf[1024];
ssize_t n;
while(1) {
if ((n = read(0, buf, 1024)) > 0) {
buf[n] = '\0';
printf("ctrlprocess receive: %s\n", buf);
if (!strcmp(buf, "exit"))
exit(0);
if (!strcmp(buf, "getpid")) {
printf("My pid: %d\n", getpid());
sleep(3);
exit(0);
}
}
}
} 执行与输出:beyes@linux-beyes:~/C/pipe> ./monitor.exe getpid
ctrlprocess receive: getpid
My pid: 9579 beyes@linux-beyes:~/C/pipe> ./monitor.exe exit
ctrlprocess receive: exit 说明:
主进程向管道中写一个命令行参数,子进程从标准输入里面读出该参数并进行相应操作。
由输出可见,被监控子进程接受监控主进程的命令,执行不同的操作。在实际项目中经常看到,监控进程启动加载多个具有不同功能的子进程,并通过管道的形式向子进程传递参数。 |
|