fork()与char数组和qsort()导致子进程停止工作

我在使用qsort()函数时遇到了一些问题。 这种情况是我之前添加的post参考的扩展。 我需要对存储成员接收元素(即卡片套装)的数组进行排序。 例如:

以下示例运行 –

 ./a.out A4 B2 CK DA BJ A3 DT C4 A2 B3 D4 C3 Child : 1, pid 18211 : A4 BJ A2 Child : 2, pid 18212 : B2 A3 B3 Child : 3, pid 18213 : CK DT D4 Child : 4, pid 18214 : C4 DA C3 Father : 4 childs created 

期望的输出

 ./a.out A4 B2 CK DA BJ A3 DT C4 A2 B3 D4 C3 Child : 1, pid 18211 : A4 A2 BJ Child : 2, pid 18212 : A3 B3 B2 Child : 3, pid 18213 : CK DT D4 Child : 4, pid 18214 : C4 C3 DA Father : 4 childs created 

即将A4 BJ A2保存在一个arrays中,在第二arrays中保存B2 A3 B3,在第三arrays中保存CK DT D4,在第四arrays中保存C4 DA C3。 并按降序对成员元素进行排序并执行进一步操作。

但是,当我尝试使用qsort时,我有以下问题:

没有子输出(即使未排序的打印语句)

问题是什么? qsort实现有什么问题吗? 请帮我。

代码到目前为止:

  #include  #include  #include  #include  #include  void childFunction( char *argv[], int argc, int identify ){ int cmp( const void *a, const void *b ){ return *(char *)a - *(char *)b; } int childnum = identify + 1 ; int i,j,r,z; char *a[256]; char *temp[256]; printf("Child : %d, pid %d : ", childnum, getpid() ); for( i = childnum; i < argc; i += 4 ) { for( j = 0; j < argc; j++ ) { a[j] = argv[i]; printf("%s ", a[j]) ; break; } } qsort(a,sizeof(a),sizeof(a[0]),cmp); printf( "\n" ) ; for( j = 0; j < sizeof(a); j++ ) { printf("%s ", a[j]) ; 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, argc, 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; } } // do stuff in the father //wait for all child created to die waitpid(-1, NULL, 0); printf("Father : %d childs created\n", i); } [1]: https://stackoverflow.com/questions/42325032/c-print-and-store-command-line-argument-in-a-round-robin-manner/42325301?noredirect=1#comment72082753_42325301 

是的,你如何调用qsort存在问题。

第二个参数是数组中的成员数。 sizeof(a)返回a的整个大小,在这种情况下是2048字节(256个元素* 8个字节用于指针)。 你真正想要的是跟踪你填充的元素的数量并使用该值。

哪种导致另一个问题,即你填充a方式没有多大意义,我看不出你是如何得到它的输出的。 你正在使用argv[i]argv[i]的不同值重复填充数组的第一个argc元素。

我在想你的意思是这样的:

 for( i = childnum; i < argc; i += 4 ) { a[j++]=a[i]; } 

然后,它将j作为传递给qsort的元素数量。

您需要阅读更多关于qsort函数以及它传递给比较函数的内容。

qsort函数将调用比较函数,将指针传递给数组中的元素。 即在你的情况下,它将调用你的function,例如

 cmp(&a[0], &a[1]); 

由于你有一个指针数组, cmp的参数是指针的指针 ,参数实际上是char **

所以你有一个无效的强制转换并减去函数中两个指针的最低字节。

如果要比较每个字符串的第一个字符,则需要在函数中使用正确的转换和解除引用:

 return **(char **)a - **(char **)b;