您的位置:首页 > 运维架构 > Linux

Linux进程管理与程序开发

2010-11-18 17:01 281 查看
1、创建进程

code:

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t pid;
if((pid=fork())==-1)	puts("fork error");
else if(pid==0)
puts("in the child");
else puts("in the parent");
return 0;
}


结果:

in the parent

in the child

2、父子进程 对打开文件的处理

notes:子进程将复制父进程的数据段、BSS、代码段、堆空间、栈空间和文件描述符

对于文件描述符关联的内核文件表项,则采用共享的方式(父子进程共享文件)

codes:

#include<sys/types.h>
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
int main()
{
pid_t pid;
int fd,i=1,status;
char * ch1="Hello";
char * ch2="world";
char * ch3=" this is Jason";
if((fd=open("doc3",O_RDWR|O_CREAT,0644))==-1){
perror("parent_open_fail");
exit(EXIT_FAILURE);
}
if(write(fd,ch1,strlen(ch1))==-1){
perror("parent_write fail");
exit(EXIT_FAILURE);
}
if((pid=fork())==-1){
perror("fork");
exit(EXIT_FAILURE);
}
else if(pid==0)	//child process
{
i=2;
puts("in child");
printf("i is %d/n",i);
if((write(fd,ch2,strlen(ch2)))==-1)
perror("child write fail");
return 0;
}
else{	//parent process
sleep(1);
puts("in parent");
printf("i is %d/n",i);
if((write(fd,ch3,strlen(ch3)))==-1)
perror("parent write fail");
wait(&status);
return 0;

}
}


结果:

Helloworld this is Jason

3、在进程中运行新的代码

该进程代码段、数据段 等等完全由新程序代替

code:

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t pid;
pid=fork();
if(pid<0)	puts("error");
else if(pid==0)	{
execl("/bin/ls","ls","-l","/code",(char*)0);
puts("the latter code in child");
}
else 	puts("father ok");
return 0;
}


结果:

father ok

root@ubuntu:/code/chap6# total 104

drwxr-xr-x 2 root root 4096 2010-11-15 16:05 chap3

drwxr-xr-x 2 root root 4096 2010-11-16 21:14 chap4

drwxr-xr-x 2 root root 4096 2010-11-17 20:50 chap5

drwxr-xr-x 2 root root 4096 2010-11-22 17:31 chap6

drwxr-xr-x 2 root root 4096 2010-11-22 15:57 chap8

-rw-r--r-- 1 root root 70 2010-11-07 16:34 fac.c

-rw-r--r-- 1 root root 1352 2010-11-07 16:41 fac.o

-rw-r--r-- 1 root root 11 2010-11-07 15:38 hello2.c

-rw-r--r-- 1 root root 75 2010-11-07 15:45 hello.c

-rw-r--r-- 1 root root 243 2010-11-16 19:49 main.c

-rw-r--r-- 1 root root 243 2010-11-07 16:40 main.c~

-rw-r--r-- 1 root root 39255 2010-11-07 17:07 main.i

-rw-r--r-- 1 root root 1768 2010-11-07 16:40 main.o

-rwxr-xr-x 1 root root 8494 2010-11-07 16:42 run

drwxr-xr-x 2 root root 4096 2010-11-07 17:41 testSpot
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐