我在使用qsort()
函数时遇到了一些问题。这种情况是我之前添加的文章reference的扩展。我需要对存储成员接收元素的数组进行排序(即适合卡片)。例如:fork()与char数组和qsort()导致孩子停止工作
用以下示例运行 -
./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在阵列中,保存B2 A3 B3在第二阵列,保存CK DT D4在第三个阵列中,将C4 DA C3保存在第四个阵列中。按降序排列成员元素并进行进一步的操作。
然而,当我尝试使用快速排序,我有以下问题:
没有子输出(即使未排序print语句)
问题是什么?在qsort实现中有没有问题? 请帮帮我。
代码至今:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
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
那么开始你的程序不是一个真正有效的C程序,因为C没有嵌套函数。 –