进程的创建仅有一个函数,也是linux下唯一能创建进程的函数:
fork()
功能:用来产生一个新进程,其子进程会复制父进程的数据和堆栈空间,并继承父继承的用户代码、组代码,环境变量、已经打开的文件代码、工作目录和资源限制。但子进程不会继承父继承的文件锁定和未处理的信号。
定义函数:pid_t fork(void)
返回值:若执行成功将在父进程返回新创建的子进程的PID,而在新创建的子进程中返回0,若失败则返回-1,失败原因在errno中。
头文件:#include
简单实例:
keven@localhost systemCall]$ cat -n fork_example.c
1 #include
2 #include
3 #include
4 #include
5 #include
6 #include
7 #include
8 #include
9 extern int errno;
10
11 int main()
12 {
13 char buf[100];
14 pid_t child_pid;
15 int fd;
16 int status;
17
18 if((fd=open("temp",O_CREAT|O_TRUNC|O_RDWR,S_IRWXU))==-1)
19 {
20 printf("open error %d",errno);
21 exit(1);
22 }
23 strcpy(buf,"This is parent process write");
24 if((child_pid=fork())==0)
25 {
26 strcpy(buf,"This is child process write");
27 printf("This is child process");
28 printf("My PID(child) is %d\n",getpid());
29 printf("My parent PID is %d\n",getppid());
30 write(fd,buf,strlen(buf));
31 close(fd);
32 exit(0);
33 }
34 else
35 {
36 printf("This is parent process");
37 printf("My PID(parent) is :%d\n",getpid());
38 printf("My child PID is %d\n",child_pid);
39 write(fd,buf,strlen(buf));
40 close(fd);
41 }
42 wait(&status);
43 return 0;
44 }
[keven@localhost systemCall]$ ./fork_example
This is child processMy PID(child) is 6207
My parent PID is 6206
This is parent processMy PID(parent) is :6206
My child PID is 6207
[keven@localhost systemCall]$
阅读(1243) | 评论(0) | 转发(0) |