裏面我的代碼我想...如何將參數從父進程傳遞給Unix中的子進程?
1)父進程會創建一個數組有至少10 元素
2)子進程將計算生產的所有元素 用陣列
3)內奇數索引的子進程將提供結果 到當它完成計算,然後子進程 將終止
父進程4)母公司將計算生產後,從子進程
5)父進程將最終輸出 結果得到 結果。
現在代碼邏輯很容易寫是向下跌破
int cal(int arr[10]) {
int i=0;
int sum = 0;
for (i=1; i<10; i=i+2) {
sum = sum + arr[i];
}
return sum;
} // end of calc
int main() {
int arr[] = { 10, 20, 25, 5, 6, 45, 87, 98, 23, 45};
int sum = cal(arr);
printf("Sum of all odd indexs element is : %d", sum);
return 0;
} // end of main
這裏是代碼使用叉創建一個子進程()
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main() {
pid t pid;
/* fork a child process */
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) { /* child process */
execlp("/bin/ls","ls",NULL);
}
else { /* parent process */
/* parent will wait for the child to complete */
wait(NULL);
printf("Child Complete");
}
return 0;
} // end of main
我的問題是。 ..
我該如何使用代碼邏輯並結合使用fork()創建子進程?如果pid == 0,那麼創建一個子進程是成功的,所以我認爲這就是我們插入第二步的代碼的地方...... 2)子進程會計算所有元素的生產 奇數索引內陣列。
父節點如何將數組發送到子進程,以便子進程可以將具有奇數索引的元素求和?
更新的代碼:我結合兩個以上驗證碼成一個
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
/*
calculate the production of all elements with odd index inside the array
*/
int cal(int arr[10]) {
int i=0;
int sum = 0;
for (i=1; i<10; i=i+2) {
sum = sum + arr[i];
}
return sum;
} // end of calc
int main() {
pid t pid;
/* fork a child process */
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) { /* child process */
print("I am the child process");
// the child process will calculate the production
// of all elements with odd index inside the array
calc();
// the child process will provide the result to the parent process
// when it finish calculation and then the child process will terminate
exit(0);
}
else { /* parent process */
/* parent will wait for the child to complete */
printf("I am the parent, waiting for the child to end");
// the parent process will create an array with at least 10 element
int arr[] = { 1, 2, 5, 5, 6, 4, 8, 9, 23, 45 };
int sum = calc(arr);
wait(NULL);
printf("Child completed calculating the production of all elements with odd index inside the array");
// the parent will calculate the production after it get the result from the child process
// the parent process will finally output the results.
printf("Sum of all odd indexs element is : %d", sum);
}
return 0;
} // end of main
所以,現在你只能通過'ls'傳遞'argv [0]'。如果您想傳遞更多參數,請將它們放在命令行中。這就是:'execlp(「/ path/to/your/executable」,「argument-that-become- $ 0」,「argument-that-become- $ 1」,「argument-that-become- $ 2」,「etc」 ,NULL)'。 –
要在2進程之間進行通信,可以使用信號('kill()'和'signal()'或'sigaction()') – YaatSuka
@YaatSuka,呃? OP不僅僅希望發送(非信息攜帶)信號,他們希望傳遞明確的值。信號沒有關於傳送順序的保證,其中有幾個含義不能被覆蓋(你不能通過'SIGKILL'傳遞'9',並且程序不以任何方式解釋爲退出,所以它沒有用作發送未知值的整數的方法)。 –