fork

来源:互联网 发布:日历软件 编辑:程序博客网 时间:2024/05/18 03:14

fork学习的小例子

============================================================================================================================

#include"include.c"

int main(){

pid_t pid;

pid=fork();

if(pid==0){

execv("pwd",NULL);

}

return 0;

}

================================================================================================================================

#include<stdio.h>

#include<stdlib.h>

#include<unistd.h>

#include<errno.h>

#include<sys/types.h>

#include<sys/wait.h>

 

int main(){

 

pid_t pit,kk;

pit=fork();

if(pit<0){

perror("fork is failure\n");

exit(1);

}

if(pit==0)//子进程中

{

printf("child!\n");

//execv("/bin/ls",NULL);

//exit(1);

}

if(pit>0){

//sleep(50);

printf("father!\n");

// kk=wait(NULL);

// printf("%d\n",kk);

}

printf("hello world!\n");

printf("pid:%d,ppid:%d\n",getpid(),getppid());

return 0;

}

===============================================================================================================================

#include"head.h"

int main(){

size_t len=30;

char name[100];

bzero(name,100);

if(gethostname(name,sizeof(name))==-1)

{

perror("is failure!");

exit(1);

}

printf("%s hello",name);

return 0;

 

}

=======================================================================================================================

#include "head.h"

int main(){

int fd;

pid_t pidd,ppid;

pidd=fork();

if(pidd<0){

perror("chongdingxiang fork is failure!");

exit(1);

}else if(pidd==0){

fd=open("aa",O_RDWR);

printf("++++++++++++++\n");

// dup2(fd,STDOUT_FILENO);

printf("----++++_____\n");

//exit(1);

execlp("ls",NULL);

}else if(pidd>0){

if(waitpid(pidd,NULL,0)<0){

perror("chongdingxiang waitpid is failure!");

exit(1);

}

}

printf("hello world!\n");

return 0;

}


原创粉丝点击