我是c編程的新手,我遇到了這個實現問題。情況是我需要使用fork()
創建4個子進程以循環方式打印命令行參數,即如果輸入是./abc.c RR GG EE WW BB CC DD AA
,子進程1應該存儲和打印RR BB
,子進程2應該存儲和打印GG CC
以及等等。最終的輸出應該是這樣的。以循環方式打印和存儲命令行參數
Child 1, pid 23460: S5 HT DK S4 H7 S6 S8 D2 H3 H2 DT DA S9
Child 2, pid 23461: C7 HA D6 S7 SQ HK H6 H4 C3 CK S2 C9 SJ
3和4子進程有類似的輸出。
問題是商店的一部分。我們如何正確存儲這些參數並使用printf或其他方法來產生上述輸出?一個子進程打印一行。我找不出解決方案。
存儲要求是存儲Child 1元素是一個數組。 S5 HT DK S4 H7 S6 S8 D2 H3 H2 DT DA S9
,將子元素2存儲在一個數組中。 C7 HA D6 S7 SQ HK H6 H4 C3 CK S2 C9 SJ
等。
這是我在這一刻得到的。
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
void childFunction(char *argv[], int identify){
int i;
for (i=1;i<sizeof(argv);i+=4){
switch (identify){
case 0:
printf("Child : %d %s\n", identify+1, argv[i]);
break;
case 1:
printf("Child : %d %s\n", identify+1, argv[i+1]);
break;
case 2:
printf("Child : %d %s\n", identify+1, argv[i+2]);
break;
case 3:
printf("Child : %d %s\n", identify+1, argv[i+3]);
break;
}
}
// do stuff
}
int main(int argc, char *argv[]){
int childLimit = 4; // number of children wanted
int childrenPids[childLimit]; // array to store children's PIDs if needed
int currentPid, i;
for(i=0; i<childLimit; i++){
switch(currentPid = fork()){
case 0:
// in the child
childFunction(argv, i);
// exit the child normally and prevent the child
// from iterating again
return 0;
case -1:
printf("Error when forking\n");
break;
default:
// in the father
childrenPids[i] = currentPid; // store current child pid
break;
}
}
printf("Father : %d childs created\n", i);
// do stuff in the father
//wait for all child created to die
waitpid(-1, NULL, 0);
}
更新要求: 我需要進一步明確的要求,這是我需要打印,保持每個子進程的部件元件在陣列用新升序排序要求。
for(i = childnum; i < argc; i += 4)
{
for(j = 0; j < argc; j++)
{
a[j] = argv[i];
printf("%s ", a[j]) ;
break;
}
}
它產生下面的輸出:
./a.out ff ee gg tt hh oo ee pp
Child : 1, pid 762 : ff hh
Child : 3, pid 764 : gg ee
Child : 2, pid 763 : ee oo
Father : 4 childs created
Child : 4, pid 765 : tt pp
輸出很好看,但如何將它們存儲在獨立陣列和
代碼根據第一個答案修改執行一些排序,即子1元素的升序?
如果您的示例輸出都是完整的(即,所有四個進程)並且與先前對示例輸入的描述相匹配,那麼這將不那麼令人困惑。 – Clifford
「商店」是什麼意思?存儲在哪裏,併爲了什麼目的? – Clifford