无名进程通信

代码如下:

/* environment:
 *  4.13.0-43-generic  x86_64, gcc 5.4.0
 * */

#include <stdio.h>
#include <unistd.h>
#include <memory.h>
//#define INPUT 0
//#define OUTPUT 1

/*
 * 无名管道进程通信
 * #include <unistd.h>
 *    int pipe(int filedis[2]);
 *    filedis[0] open for read
 *    filedis[1] open for write
 *
 * */
int main() {

    int file_desc[2];

    //save the retVal of fork()
    pid_t  child_pid;
    char buf[256]={'0'};
    int return_count;

    //create unnamed process
    pipe(file_desc);

    //create child process
    /*
     * 如果创建成功一个子进程,对于父进程来说是返回子进程的ID.而对于子进程来说就是返回0.而返回-1代表创建子进程失败.
     *
     * */
    child_pid = fork();

    if(child_pid == -1) {
        printf("create process failed!\n");
    }

    if(child_pid == 0){//create process success
        //关闭管道的端口
        close(file_desc[0]);
        write(file_desc[1],"test-data",strlen("test-data"));
        printf("current process is : %d Hello, World!\n",getpid());

    }else{
        close(file_desc[1]);
        return_count = (int) read(file_desc[0], buf, sizeof(buf));

        printf("current process is : %d  from child process '%s',size=%d(byte)\n",getpid(),buf,return_count);
    }

    printf("current process is : %d Hello, World!\n",getpid());

    return 0;
}

  结果:

分析:

  fork() 产生了一个新的进程,并且复制了执行进程的堆栈信息。
最后从 child_pid = fork()开始,代码在2个进程中执行。
父进程取得了子进程传过来的数据。
原理参考:https://www.linuxidc.com/Linux/2016-10/136542.htm

猜你喜欢

转载自www.cnblogs.com/fangzirui/p/9364253.html