多进程编程例子1:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
pid_t pid;
//pid = fork();
if((pid=fork())==-1) {
printf("fork error\n");
return -1;
}
else if(pid==0) {
while(1) {
printf("In the child process\n"); sleep(1); }
}
else {
while(1) {
printf("In the parent process\n"); sleep(1); }
}
return 0;
}
多进程编程例子2:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
pid_t pid;
int i=1;
int fd;
int status;
char *t1="hello";
char *t2="test";
char *t3="now\n";
fd=open("test.txt",O_RDWR | O_CREAT, 0644);
if(fd<0) {
perror("parent open error\n");
exit(EXIT_FAILURE);
}
if((write(fd,t1,strlen(t1)))<0) {
perror("parent write error\n");
exit(EXIT_FAILURE);
}
printf("current pid=%d\n",getpid());
pid = fork();
if(pid<0) {
perror("fork error\n");
exit(EXIT_FAILURE);
}
else if(pid==0) {
i=2;
if((write(fd,t2,strlen(t2)))<0) perror("child write error\n");
printf("in child i=%d,cid=%d,pcid=%d\n",i,getpid(),getppid());
return 0;
}
else {
sleep(1);
if((write(fd,t3,strlen(t3)))<0) perror("parent write error\n");
printf("in parent i=%d,pid=%d\n",i,getpid());
wait(&status);
return 0;
}
}
运行结果:
test.txt内容:hellotestnow
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。