您的位置:首页 > 其它

用fork系统调用,clone系统调用

2010-04-05 15:54 260 查看
来一段C代码,用fork创建一个子进程

Code:

#include <unistd.h>

#include <stdio.h>

int main( int argc, char **argv)

{

int a=10;

pid_t pid;

printf("before fork pid=%d/n",getpid());

pid = fork();

if( pid<0){

printf("fork failed!/n");

return -1;

}

if ( pid == 0 ){

a++;

printf("This is child process! parent pid=%d,my pid=%d, pid=%d, a=%d/n",getppid(),getpid(),pid,a);

}

else{

printf("This is parent process! my pid=%d, child pid=%d, a=%d/n", getpid(), pid,a);

}

return 0;

}

编译:[root@localhost /]# gcc -o fork fork.c

结果:

[root@localhost /]# ./fork

before fork pid=23703

This is child process! parent pid=23703,my pid=23704, pid=0, a=11

This is parent process! my pid=23703, child pid=23704, a=10

再来一段,clone系统调用

Code:

#include <stdlib.h>

#include <sched.h>

#include <signal.h>

#include <unistd.h>

#include <malloc.h>

#include <fcntl.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <sys/wait.h>

char *prog_argv[4];

int foo;

int fd;

#define CHILD_STACK (1024*64)

int thread_function(void *argument)

{

printf("CHILD:child thread begin.../n");

foo=2008;

close(fd);

execvp(prog_argv[0],prog_argv);

printf("CHILD:child thread exit , this line won't print out./n");

return 0;

}

int main()

{

char c;

char *stack;

pid_t pid;

foo=2007;

fd=open("/etc/passwd",O_RDONLY);

if(fd<0){

perror("open");

exit(-1);

}

printf("PARIENT : the variable foo was :%d /n",foo);

if(read(fd,&c,1)<1){

perror("PARIENT:File read error/n");

exit(1);

}

else

printf("PARIENT : We could read from the file:%c/n",c);

prog_argv[0]="/bin/ls";

prog_argv[1]="-1";

prog_argv[2]="/";

prog_argv[3]="NULL";

stack = (char*)malloc(CHILD_STACK);

if(stack == NULL){

perror("malloc : could not allocate stack");

exit(2);

}

printf("PARENT:Creating child thread/n");

pid=clone(thread_function,(void*)(stack+CHILD_STACK),

SIGCHLD|CLONE_FS|CLONE_SIGHAND|CLONE_VM,NULL);

if(pid == -1){

perror("clone");

exit(3);

}

printf("PARENT:Waiting for the finish of child thread :%d /n",pid);

pid=waitpid(pid,0,0);

if(pid == -1){

perror("wait");

exit(4);

}

free(stack);

printf("PARENT:Child thread returned and stack free./n");

printf("PARENT:The variable foo now is %d/n",foo);

if(read(fd,&c,1)<1){

perror("PARENT:File read error/n");

exit(5);

}

}

else

printf("PARENT:we could read from file:%c/n",c);

return 0;

}

编译,执行:

[root@localhost /]# gcc -o clone clone.c -lpthread

[root@localhost /]# ./clone

PARIENT : the variable foo was :2007

PARIENT : We could read from the file:r

PARENT:Creating child thread

PARENT:Waiting for the finish of child thread :24951

CHILD:child thread begin...

CHILD:child thread exit , this line won't print out.

PARENT:Child thread returned and stack free.

PARENT:The variable foo now is 2008

PARENT:we could read from file:o
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: