プロセス制御編コード例(復習)


/*        */

#include "Process.h"  /*         */

int main()
{
	pid_t pid;

	printf("Fork pid:%d
",getpid()); pid = fork(); if(-1 == pid) { perror("fork"); exit(1); } else if(0 == pid) { printf("Child Process!
"); printf("Child Pid:%d
",getpid()); } else { printf("Parent Process!
"); printf("Parent Pid:%d
",getpid()); waitpid(pid,NULL,0); // } return 0; } /* 1. , , ? ? */ /* : waitpid(); , */ /* 2. , . 1 */ /* fork2.c */ /* fork ? */ #include "Process.h" // int main() { pid_t pid; int count = 0; pid = fork(); if(-1 == pid) // -1, { perror("fork"); exit(1); } else if(0 == pid) // 0, { count++; printf("Child count :%d
",count); } else // , { count++; printf("Parent count :%d
",count); waitpid(pid,NULL,0); } return 0; } /* : 1. ; 2. " " 3. */ /* vfork */ /* 1.vfork ? 2.vfork fork */ #include "Process.h" int main() { pid_t pid; int count = 0; pid = vfork(); if(-1 == pid) { perror("vfork"); exit(1); } else if(0 == pid) { printf("Child Process!
"); count++; printf("Child count :%d
",count); exit(2); // } else { printf("Parent Process!
"); count++; printf("Parent count :%d
",count); } return 0; } /* vfork : 1. ( fork ) 2. , ( fork ) 3. ( fork ) 4. , fork : */ /* vfork : */ #include "Process.h" int main() { pid_t pid; pid = vfork(); if(-1 == pid) { perror("vfork"); exit(1); } else if(0 == pid) { printf("Child Pid:%d
",getpid()); execl("/mnt/hgfs/share/example/Linux/process/fork","./fork",NULL); // ./fork } else { printf("Parent Process!
"); } return 0; } /* vfork */ /* */ /* waitpid.c */ #include "Process.h" void ChildRead() { int fd,ret; char buf[20] = {0}; fd = open("hello.txt",O_RDONLY); if(-1 == fd) { perror("open1"); exit(2); } ret = read(fd,buf,sizeof(buf)); if(-1 == ret) { perror("read"); exit(3); } else { printf("Read from txt:%s
",buf); memset(buf,0,sizeof(buf)); } close(fd); } void ParentWrite() { int fd; int ret; char buf[20] = {0}; fd = open("hello.txt",O_CREAT | O_WRONLY); if(-1 == fd) { perror("open2"); exit(4); } printf("Please input the string:
"); scanf("%s",buf); ret = write(fd,buf,strlen(buf)); if(-1 == ret) { perror("write"); exit(5); } close(fd); } int main() { pid_t pid; pid = fork(); if(-1 == pid) { perror("fork"); exit(1); } else if(0 == pid) { sleep(4); ChildRead(); } else { ParentWrite(); waitpid(pid,NULL,0); } return 0; }