多进程和多线程差不多,可以同时处理多件事情,不过多进程创建后相当于把代码拷贝一份,数据不互通
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t id;
int i;
printf("pid:%d\n",getpid());//打印当前进程id
id=fork();
printf("id:%d pid:%d\n",id,getpid());
if(id>0)
{
while(1)
{
printf("father run!\n");
sleep(2);
}
exit(0);
}
else if(id==0)
{
while(1)
{
printf("child run!\n");
scanf("%d",&i);
printf("child i=%d",i);
sleep(2);
}
exit(0);
}
else
{
printf("fork error!\n");
}
}
创建一个进程创建文件,使用另一个进程删除文件,代码如下:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include<sys/stat.h>
#include<fcntl.h>
int main()
{
pid_t id;
int fd;
char buf[128];
id=fork();
if(id>0)
{
while(1)
{
fd=open("file1",O_WRONLY|O_CREAT,0777);
if(fd<0)
{
perror("open");
exit(0);
}
printf("file1 create!\n");
sleep(2);
}
exit(0);
}
else if(id==0)
{
while(1)
{
system("rm file1");
printf("file1 del!\n");
sleep(2);
}
exit(0);
}
else
{
printf("fork error!\n");
}
}