[운영체제] fork() 사용하기
1. 다음 프로그램을 실행해보시오.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
char *name = argv[0];
int child_pid = fork();
if(child_pid == 0){
printf("Child of %s is %d\n", name, child_pid);
return 0;
}
else{
printf("My child is %d\n", child_pid);
return 0;
}
}
Q. 실행결과는?
My child is 20134
Child of ./child_fork is 0
2. 두 개의 자식 프로세스를 생성한 후, 부모 프로세스는 'P'를 출력하고, 첫 번째 자식 프로세스는 'A', 두 번째 자식 프로세스는 'B'를 각각 100,000번씩 출력하고 종료하는 프로그램을 작성하시오.
* 프로그램 소스코드:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char*argv[])
{
char *name=argv[0];
int A=fork();
if(A == 0){
for(int i=1;i<=100000;i++){
printf("A");
}
return 0;
}
int B=fork();
if(B == 0){
for(int i=1;i<=100000;i++) {
printf("B");
}
return 0;
}
else{
for(int i=1;i<=100000;i++) {
printf("P");
}
return 0;
}
}
3. 다음 프로그램을 실행하고 전체 몇 개의 프로세스가 생성되는지 확인하시오.
#include <unistd.h>
int main(void)
{
fork();
fork();
fork();
printf("Hello\n");
return 0;
}
Q. 생성되는 프로세스의 수는?
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
총 8개가 생성된다.
4. 두 개의 자식 프로세스를 생성한 후, 첫 번째 자식 프로세스는 'A', 두 번째 자식 프로세스는 'B'를 각각 100,000번씩 출력하고 종료하며, 부모 프로세스는 두 자식 프로세스가 모두 종료한 후 "My children have gone." 메시지를 출력하고 종료하는 프로그램을 작성하시오.
[Hint]
#include <sys/wait.h>
pid_t wait(int *statloc);
pid_t waitpid(pid_t pid, int *statloc, int options);
Both return: process ID if OK, 0 , or -1 on error
예)
int status;
wait(&status);
*프로그램 소스 코드:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char*argv[])
{
char *name=argv[0];
int A=fork();
int status;
if(A == 0){
for(int i=1;i<=100000;i++){
printf("A");
}
return 0;
}
int B=fork();
if(B == 0){
for(int i=1;i<=100000;i++) {
printf("B");
}
return 0;
}
wait(&status);
wait(&status);
printf("My children have gone.\n");
return 0;
}
5. 'ps -edf | grep 본인id' 명령어를 사용하여 본인 소유의 프로세스를 모두 종료하시오.
종료 방법: kill -9 프로세스id