我想从子进程向父进程发送数据。 我做管道并尝试发送数据,它正在工作。但是如何看待这个子流程在父流程中完成了它的工作呢?
我的代码是:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char **argv){
pid_t pid;
int status;
int i;
int pipe[2];
char buf[1];
char *envp[] = {NULL};
char *arg[] = {NULL, "2", NULL};
int res;
if(argc != 3){
exit(EXIT_FAILURE);
}
if(pipe2(pipe, 0) == -1){
printf("-1 : %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
arg[0] = argv[1];
// for(i = 0; i < argc; i++){
// printf("argv[%d]: %s\n", i, argv[i]);
// }
pid = fork();
if(pid == -1){
printf("1 : %s", strerror(errno));
exit(EXIT_FAILURE);
}
if(pid == 0){
printf("child start\n");
close(pipe[0]);
dup2(pipe[1], 1);
if(-1 == execvp(argv[1], arg)){
printf("2 : %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
printf("child end\n");
exit(0);
} else {
do{
res = read(pipe[0], buf, 1);
printf("read some info\n");
if(res == -1){
printf("%s\n", strerror(errno));
break;
} else if(res == 0) {
printf("end\n");
break;
} else {
if(*buf == EOF){
printf("EOF\n");
}
printf("char: %c\n", *buf);
}
} while(1);
close(pipe[0]);
printf("parent end\n");// in the parent
}
return 0;
}
第二个应用程序的代码是:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
int i;
int nmbr;
for(i = 0; i < argc; i++){
printf("g: argv[%d]: %s\n", i, argv[i]);
}
if(argc < 2){
exit(EXIT_FAILURE);
}
printf("Hello from gen_test\n");
nmbr = atoi(argv[1]);
for(i = 0; i < nmbr; i++){
printf("0");
//sleep(1);
}
exit(EXIT_SUCCESS);
}
我将此应用用作
brainiac@brainiac-Latitude-7480:~/workspace/linux_fund$ ./solution ./a.out 2
child start
read some info
char: g
read some info
char: :
read some info
char:
read some info
char: a
read some info
char: r
read some info
char: g
read some info
char: v
read some info
char: [
read some info
char: 0
read some info
char: ]
read some info
char: :
read some info
char:
read some info
char: .
read some info
char: /
read some info
char: a
read some info
char: .
read some info
char: o
read some info
char: u
read some info
char: t
read some info
char:
read some info
char: g
read some info
char: :
read some info
char:
read some info
char: a
read some info
char: r
read some info
char: g
read some info
char: v
read some info
char: [
read some info
char: 1
read some info
char: ]
read some info
char: :
read some info
char:
read some info
char: 2
read some info
char:
read some info
char: H
read some info
char: e
read some info
char: l
read some info
char: l
read some info
char: o
read some info
char:
read some info
char: f
read some info
char: r
read some info
char: o
read some info
char: m
read some info
char:
read some info
char: g
read some info
char: e
read some info
char: n
read some info
char: _
read some info
char: t
read some info
char: e
read some info
char: s
read some info
char: t
read some info
char:
read some info
char: 0
read some info
char: 0
^C
但是当子应用程序关闭时,我不能在父进程中和函数读取得到返回值零,我不知道为什么。需要帮助或任何建议。