父母/子女和管道以C方式进行,子女与父母的交流

时间:2019-10-19 21:13:49

标签: c linux pipe execl

我有一个父程序,该程序将整数发送给孩子,并且子程序将数字乘以2并返回给父变量

在主程序中,我创建一个pipe和fork()并在子对象上执行execl(),在切换之后,我将值通过pip传递给child中的child,我可以得到该值,但是如何获取在执行execl()之后将结果从子级返回到父级?

child.c
#include <stdio.h> 
#include <stdlib.h>
#include <unistd.h>

int main(){
int fd,nread,result;
char data[20];
fd=atoi(argv[1]);
nread=read(fd,data,sizeof(data));
switch(nread)
{
    case -1:
        break;
    default:
         result=atoi(data)*2;
         sprintf(result,"%d",(result));
         //how can here return data to the parent?
         break;

}
}

2 个答案:

答案 0 :(得分:0)

此时在代码中:

//how can here return data to the parent?

插入语句:

return result;

并消除对sprintf()

的呼叫

然后在父进程中:

int status;
waitpid( pid, &status );
printf( "%d\n", status );

答案 1 :(得分:0)

使用两个管道。

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

void xclose(int fd);
void xdup2(int a, int b);
int
main(int argc, char **argv)
{
        int p1[2];
        int p2[2];
        int val = argc > 1 ? strtol(argv[1], NULL, 10) : 1;
        char buf[128];
        int len;
        ssize_t rc;
        if(pipe(p1) || pipe(p2)) {
                perror("pipe");
                return EXIT_FAILURE;
        }
        switch(fork()) {
        case -1:
                perror("fork");
                return EXIT_FAILURE;
        case 0:
                xdup2(p1[0],STDIN_FILENO);
                xclose(p1[0]);
                xclose(p1[1]);
                xdup2(p2[1],STDOUT_FILENO);
                xclose(p2[0]);
                xclose(p2[1]);
                execlp("awk", "awk", "{print $1 * 2}", NULL);
                perror("exec");
                return EXIT_FAILURE;
       default:
                len = sprintf(buf, "%d", val);
                write(p1[1], buf, len);
                xclose(p1[1]);
                xclose(p1[0]);
                xclose(p2[1]);
                if(( rc = read(p2[0], buf, sizeof buf)) == -1) {
                        perror("read");
                }
                xclose(p2[0]);
                buf[rc] = '\0';
                printf("%s", buf);
        }
        return EXIT_SUCCESS;
}

void
xclose(int fd) {
        if(close(fd)) {
                perror("close");
                exit(EXIT_FAILURE);
        }
}
void
xdup2(int a, int b) {
        if(dup2(a,b) == -1) {
                perror("dup2");
                exit(EXIT_FAILURE);
        }
}