這是我在 C 中的代碼系統呼叫。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int n;
int i;
pid_t pid;
int time = 1000;
int sum = 0;
int main(void) {
printf("n: ");
scanf("%d", &n);
pid = fork();
if (pid < 0) {
printf("Fork Failed");
exit(-1);
} else if (pid == 0) {
//child
for (i = 1; i <= n; i ) {
sum = i;
}
printf("Sum of 1 to %d: %d\n", n, sum); // this is ok
} else {
// parent
wait(&time);
printf("Sum of 1 to %d: %d\n", n, sum); // this always return 0;
}
return 0;
}
我不知道為什么在父母的代碼塊中,總和總是等于0。如何讓父母等待孩子或者我做錯了什么?
uj5u.com熱心網友回復:
等待孩子的作品。然而,你的期望是錯誤的。
顯然,您認為分叉后子行程中的計算在父行程中是可見的。他們不是。在 fork 時,子程式是父程式的新副本。那時,父母的sum為0并保持這種狀態。
有幾種機制可以將資料從子節點傳遞給父節點(搜索詞是行程間通信,IPC)。
- 退出()狀態
- 檔案
- 共享記憶體
- 管道
- 信號
- 訊息佇列
- 我還錯過了什么
uj5u.com熱心網友回復:
這里的問題是變數sum不被父子行程共享,在 fork() 呼叫之后,子行程將擁有自己的變數 sum 副本。使用來自POSIX api的shmget(),shmat() 。或者使用pthread它將為新創建的執行緒共享相同的記憶體空間。更新---將共享記憶體添加到您的代碼中希望這會有所幫助。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/shm.h>
int n;
int i;
pid_t pid;
int time = 1000;
int main(void) {
int shmid;
int *sum;
printf("n: ");
scanf("%d", &n);
/*request the shared memory from the OS using the shmget()*/
shmid = shmget(IPC_PRIVATE, sizeof(int), 0777|IPC_CREAT);
pid = fork();
if (pid < 0) {
printf("Fork Failed");
exit(-1);
} else if (pid == 0) {
//child
/* shmat() returns a char pointer which is typecast here
to int and the address is stored in the int pointer. */
sum = (int *) shmat(shmid, 0, 0);
for (i = 1; i <= n; i ) {
*sum = i;
}
printf("Sum of 1 to %d: %d\n", n, *sum); // this is ok
/* each process should "detach" itself from the
shared memory after it is used */
shmdt(sum);
} else {
// parent
wait(&time);
sum = (int *) shmat(shmid, 0, 0);
printf("Sum of 1 to %d: %d\n", n, *sum); // this always return 0;
shmdt(sum);
/*delete the cretaed shared memory*/
shmctl(shmid, IPC_RMID, 0);
}
return 0;
}
有關更多資訊,請參閱 - https://man7.org/linux/man-pages/man2/shmget.2.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/419672.html
標籤:
上一篇:如何撰寫線性反饋移位暫存器
下一篇:不在c中輸入
