iT邦幫忙

0

請問這個問題,有人可以幫忙嗎?

依據程式,建立CentOS中加以執行,觀察執行結果後研判在標註 A/B/C/D 四處之輸出的值將各為什麼? 並加以說明。(假設其中各行程原有 pid 值,父行程為 6200,而子行程為 6203)
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
[student@iStudent ~]$ ls
a.out test2.c test.c 公共 影片 桌面 音樂
homework.c test3.c 下載 圖片 文件 模板
[student@iStudent ~]$ cc homework.c
[student@iStudent ~]$ ./a.out
child: pid = 0child: pid1 = 3074parent: pid = 3074parent: pid1 = 3073[student@iStudent ~]$
int main()
{
pid_t pid, pid1;
/* fork a child process /
pid = fork();
if (pid < 0) { /
error occurred /
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) { /
child process /
pid1 = getpid();
printf("child: pid = %d",pid); /
A /
printf("child: pid1 = %d",pid1); /
B /
}
else { /
parent process /
pid1 = getpid();
printf("parent: pid = %d",pid); /
C /
printf("parent: pid1 = %d",pid1); /
D */
wait(NULL);
}
return 0;
}
以下是我跑出來的結果:
[student@iStudent ~]$ ls
a.out test2.c test.c 公共 影片 桌面 音樂
homework.c test3.c 下載 圖片 文件 模板
[student@iStudent ~]$ cc homework.c
[student@iStudent ~]$ ./a.out
child: pid = 0child: pid1 = 3074parent: pid = 3074parent: pid1 = 3073[student@iStudent ~]$

請問有高手可以幫我指正哪邊錯誤嗎?感恩!

froce iT邦大師 1 級 ‧ 2021-07-16 16:03:09 檢舉
你老師要你了解fork()是在幹麻,本來pid就不可能跟他舉的例一樣...
這程式跑的結果沒錯。

看不懂的話建議重修,結案。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
海綿寶寶
iT邦大神 1 級 ‧ 2021-07-16 17:53:04

https://ithelp.ithome.com.tw/upload/images/20210716/20001787jcfbfGOUVV.png

程式改成

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
	pid_t pid, pid1;
	/* fork a child process */
	pid = fork();
	if (pid < 0) { /* error occurred */
		fprintf(stderr, "Fork Failed");
		return 1;
	}
	else if (pid == 0) { /* child process */
		pid1 = getpid();
		printf("(A)child: pid = %d\n",pid); /* A */
		printf("(B)child: pid1 = %d\n",pid1); /* B */
	}
	else { /* parent process */
		pid1 = getpid();
		printf("(C)parent: pid = %d\n",pid); /* C */
		printf("(D)parent: pid1 = %d\n",pid1); /* D */
// 		wait(NULL);
	}
	return 0;
}

執行結果

(C)parent: pid = 80651
(D)parent: pid1 = 80649
(A)child: pid = 0
(B)child: pid1 = 80651

對照題目(6200, 6203),可得

A=0
B=6203
C=6203
D=6200
wen1112 iT邦新手 5 級 ‧ 2021-07-18 10:42:44 檢舉

所以有的是系統呼叫出來的,有的是程式裡印出的值?是這樣嗎?謝謝!

我不確定你指的「系統呼叫出來的」是什麼意思
不過有的是程式裡印出的值是這樣的沒錯

wen1112 iT邦新手 5 級 ‧ 2021-07-18 19:45:10 檢舉

就是預設的父行程子行程

我要發表回答

立即登入回答