【发布时间】:2015-10-11 21:03:27
【问题描述】:
我正在尝试使用单独的进程计算当前目录中每个二进制文件的校验和以提高性能。但是,出于某种原因,我的输出总是出乎意料。
如何为每个文件创建一个单独的进程?我应该在 while(pids[i] != -1) 内完成整个分叉过程吗?
file_cnt = number of .bin files in the current dir
pid_t pids[file_cnt];
for(i = 0; i < file_cnt; i++)
{
if((pids[i]=fork()) < 0)
{
printf("Error forking");
return 0;
}
else if(pids[i]==0)
{
printf("Entering child \n");
printf("%s ", filenames[i]);
//reading file
handle = open( filenames[i], O_RDONLY );
//allocating memory
buffer = malloc( BUFFER_SIZE );
checksum = 0;
do
{
//calculating checksum
} while( length );
printf( " -%d\n", checksum);
printf("Exiting child \n");
}
}
我的目录中有三个文件,我的输出结果如下:
There are 3 files:
Entering child
whateve2.bin -10540
Exiting child
Entering child
Entering child
whatever.bin -8399
Exiting child
whatever3.bin -34871
Exiting child
Entering child
whatever.bin -8399
Exiting child
vab@Vaibhav:~/CS330$ Entering child
whatever3.bin -34871
Exiting child
Entering child
whatever3.bin -34871
Exiting child
Entering child
whatever3.bin -34871
Exiting child
【问题讨论】:
-
您的代码打印出
Exiting child,但不会退出子进程。 -
如果没有被信号杀死,进程在到达
main结尾或调用exit()时退出。 -
始终检查 (!=NULL) malloc() 的返回值以确保操作成功。始终检查 (>=0) open() 的返回值以确保操作成功。
-
每个孩子需要
close()输入文件并将malloc的内存传递给free()并调用exit(0); -
校验和通常不是有符号值。所以它应该被声明为
unsigned int checksum;并且应该被打印为“%8X”。为什么 printf() 语句的格式说明符前面有一个“-”?
标签: c fork child-process