C以循环方式打印和存储命令行参数

我是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 ,将Child 2元素存储在一个arrays中。 C7 HA D6 S7 SQ HK H6 H4 C3 CK S2 C9 SJ等。

这是我现在所拥有的。

 #include  #include  #include  #include  #include  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 

输出看起来很棒,但是如何将它们存储在单独的数组中并执行一些排序 ,即Child 1元素的升序?

childFunction()如果迭代从identify + 1开始,则迭代索引可以直接用于选择参数而无需切换,因此:

 void childFunction( char *argv[], int argc, int identify ) { int childnum = identify + 1 ; printf("Child : %d, pid %d : ", childnum, getpid() ); for( int i = childnum; i < argc; i += 4 ) { printf("%s ", argv[i] ) ; } printf( "\n" ) ; } 

注意需要将argc传递给chiledFunction() ; sizeof(argv)不是参数个数的计数 - 它是char**指针的大小; 在你的main() ,应该改变调用:

  childFunction(argv, argc, i); 

另一个建议的更改是在waitpid() 之后输出父文本:

  //wait for all child created to die waitpid(-1, NULL, 0); printf("Father : %d children created\n", i); 

否则它的输出可能出现在子进程的中间。

建议的更改导致以下(在我的测试中):

 sh-4.2$ main 11 22 33 44 55 66 77 88 Child : 1, pid 156 : 11 55 Child : 3, pid 158 : 33 77 Child : 2, pid 157 : 22 66 Child : 4, pid 159 : 44 88 Father : 4 children created 

请注意,子执行的顺序不是确定性的。 在上面的例子中,顺序是1,3,2,4,但在其他测试中,顺序是1,2,3,4-YMMV。