Linux C语言进程 fork函数及管道

Linux C语言创建子进程比较方便。
以下代码均需在Linux环境下运行
利用fork()函数
fork函数会返回两次。当返回值为0,即为子进程。返回值为1,为父进程。

另外 getpid()可以返回当前进程id。

int main()
{
        pid_t pid;
        pid = fork();//创建进程 获取id
        if (pid == 0)//子进程
        {
                printf("i am the child process, my process id is %d\n", getpid());//打印进程id
        }
        else//父进程
        {
                printf("i am the parent of pid: %d,my process id is %d\n", pid, getpid());//打印进程id
        }
}

管道是用于两个进程通信。进程之间默认是不分享内存的,而线程则是共享内存。
管道是一端写,一段读。如果需要双向通信就需要两条管道。
pipe(int [2])
读之前需关闭写端close(pipe_default[1])。写之前关闭读端close(pipe_default[0])。

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

int pipe_default[2]; //管道
char buffer[32];     //字符串

int main()
{
        if (pipe(pipe_default) < 0) //创建管道
        {
                printf("pipe error\n");
                return 0;
        }
        pid_t pid;
        pid = fork(); //创建进程 获取id

        if (pid < 0)
                printf("error in fork!");
        else if (pid == 0) //子进程
        {
                printf("i am the child process, my process id is %d\n", getpid()); //打印进程id
                close(pipe_default[1]);  //关闭写端  准备读          //关闭写端口,开始读内容
                if (read(pipe_default[0], buffer, 32) > 0)                         //从管道读信息 写入buffer中
                {
                        printf("receive data from parent: %s\n", buffer);
                }
        }
        else //父进程
        {
                printf("i am the parent of pid: %d,my process id is %d\n", pid, getpid());            //打印进程id
                close(pipe_default[0]);   //读端  =准备写        //关闭读端口,开始写内容
                if (-1 != write(pipe_default[1], "hello(from parent)", strlen("hello(from parent)"))) //写入信息
                {
                        printf("send data to child\n");
                }
        }
}

结果

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值