Linux进程间通信 [英] Linux interprocess communication

查看:212
本文介绍了Linux进程间通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在子进程和父进程之间进行通信,但是它不起作用.
子函数仅执行而不进入父函数

我尝试过的事情:

I want to communicate between child process and parent process but it is not working .
The child function only executing and not going into the parent function

What I have tried:

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

int main(int argc, char const *argv[])
{
    int _pipe[2];
    char arr[30];
    int pid;

    pipe(_pipe);

    pid=fork();

    if(pid==0)
    {
        while(1)
        {
            write(_pipe[1],"Hello world",100);
            printf("child process\n");
            sleep(1);
        }
    }
    else if(pid>0)
    {
        wait(NULL);
        while(1)
        {
             printf("parent process\n");
            read(_pipe[0],arr,sizeof(arr));
            printf("%s",arr);
            sleep(1);
        }
    }

    
    return 0;
}

推荐答案

该资源是通过调用 ^ ],并且在子进程中具有无限的while循环. wait()调用将阻止父级,直到子级终止或通过信号停止/恢复.但这在您的代码中永远不会发生.

另请注意,管道的未使用端应关闭,并且您将发送从未接收到的垃圾数据(您正在发送100个字节,但仅接收30个字节).仅发送必要的字节数(此处为字符串长度加一),并使用足够大以容纳最大值的接收缓冲区.可能发送的字节数.

另请参见 6.2.2在C中创建管道 [
That is sourced by calling wait(2) - Linux manual page[^] and having an infinite while loop in your child process. The wait() call will block the parent until the child terminates or stopps / resumes by a signal. But that never happens in your code.

Note also that the unused side of a pipe should be closed and you are sending junk data which are never received (you are sending 100 bytes but receive only 30). Send only the number of bytes that are necessary (string length plus one here) and use a receive buffer that is large enough to hold the max. number of bytes that might be send.

See also 6.2.2 Creating Pipes in C[^].


请参见

这篇关于Linux进程间通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆