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");
}
}
}