1:进程的创建
fork创建进程(ubuntu14.04 CodeBlock13.12)
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main(void)
{
int local_int = 8;
pid_t pid;
pid = fork();
if(pid == 0)
{
printf("This is the child process\n");
local_int = 1;
printf("Child num is %d\n",local_int);
}
else
{
sleep(2);
printf("This is the parent process\n");
printf("Parent num is %d\n",local_int);
}
printf("==================\n");
return 0;
}
有以上可以看出,子继承将父进程的数据空间、堆、栈复制,只是一个副本;
另外fork下所有代码复制各个进程空间之下,fork效率比较高,采用的是写时拷贝,也就是
也就是只有进程空间的各段的内容要发生变化时,才会将父进程的内容复制一份给子进程。
Pastedfrom <http://www.cnblogs.com/biyeymyhjob/archive/2012/07/20/2601655.html>
2:进程间的通信
管道(有名管道和无名管道) 共享内存 信号 信号量 消息队列
2.1 管道
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
int main()
{
int pipe_fd[2];
char r_buf[10];
char w_buf[10];
int local_int = 8;
pid_t pid;
memset(r_buf,0,sizeof(r_buf));
memset(w_buf,0,sizeof(w_buf));
pipe(pipe_fd);
pid = fork();
if(pid == 0)
{
printf("This is the child process\n");
local_int = 1;
int r_num;
printf("Child num is %d\n",local_int);
sleep(1);
//r_num=read(pipe_fd[0],r_buf,sizeof(r_buf)/sizeof(r_buf[0]));
r_num=read(pipe_fd[0],r_buf,100);
printf("read num is %d,and the data is%d\n",r_num,atoi(r_buf));
close(pipe_fd[0]);
}
else
{
close(pipe_fd[0]);
strcpy(w_buf,"111");
write(pipe_fd[1],w_buf,strlen(w_buf));
close(pipe_fd[1]);
printf("parent write is over\n");
sleep(3);
printf("This is the parent process\n");
printf("Parent num is %d\n",local_int);
}
printf("==================\n");
return 0;
}
Pipe_fd[0]为读端,pipe_fd[1]为写端。
注意:
1)读完之后管道的数据就不存在,最好放到一个变量中
2)如果读进程不读走管道缓冲区中的数据,那么写操作将一直阻塞。
3)如果写进程不向管道缓冲区中的写数据,那么读操作将一直阻塞。
有名管道
intmkfifo(const char * pathname, mode_t mode)
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
#defineFIFO_SERVER "/tmp/fifoserver"
int main(void)
{
int local_int = 8;
pid_t pid;
char w_buf[20];
char r_buf[20];
int fd;
memset(w_buf,2,sizeof(w_buf));
memset(r_buf,0,sizeof(r_buf));
if((mkfifo(FIFO_SERVER,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))
printf("cannot create fifoserver\n");
fd=open(FIFO_SERVER,O_RDWR,0);
pid = fork();
if(pid == 0)
{
int real_wnum=0;
printf("This is the child process\n");
local_int = 1;
strcpy(w_buf,"111");
real_wnum=write(fd,w_buf,strlen(w_buf));
printf("real_wnum= %d\n",real_wnum);
printf("Child num is %d\n",local_int);
}
else
{
int real_rnum = 0;
sleep(2);
printf("This is the parent process\n");
real_rnum = read(fd,r_buf,sizeof(r_buf));
printf("real_rnum= %d\n",real_rnum);
printf("real_rnum %d,and the data is%d\n",real_rnum,atoi(r_buf));
printf("Parent num is %d\n",local_int);
close(fd);
}
printf("==================\n");
return 0;
}
管道的区别:
1)无名管道没有名字,只能用于亲缘关系的进程间通信
2)有名管道是以文件形式存在在文件系统中,只要访问该路径,就可以相互通信
Pastedfrom <http://www.ibm.com/developerworks/cn/linux/l-ipc/part1/>