使用fork系统调用计算字符串长度的C程序错误排查求助
使用fork计算输入字符串总字符数的C程序编译错误修复
我需要编写一个使用fork系统调用的C程序,用于计算输入字符串的总字符数。程序运行方式为执行foo后跟上目标字符串,例如输入foo stack overflow时,输出应为13。我的代码如下:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { int i; int sum = 0; int status; int len; char str; for (i = 0; i < argc; i++) { int pid = fork(); if (pid < 0) { perror("fork() failed"); exit(1);} else if (pid == 0) { str = argv[i]; len = strlen(str); sum = sum + len; exit(1);} else{ exit(1);}} printf("The length of all the args is %d\n, sum"); return 0;}
编译时出现以下错误:
main.c: In function ‘main’: main.c:21:12: warning: implicit declaration of function ‘fork’ [- Wimplicit-function-declaration] 21 | int pid = fork(); | ^~~~ main.c:28:9: warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion] 28 | str = argv[i]; | ^ main.c:29:18: warning: passing argument 1 of ‘strlen’ makes pointer from integer without a cast [-Wint-conversion] 29 | len = strlen(str); | ^~~ | | | char In file included from main.c:11: /usr/include/string.h:385:35: note: expected ‘const char *’ but argument is of type ‘char’ 385 | extern size_t strlen (const char *__s) | ~~~~~~~~~~~~^~~ main.c:36:40: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=] 36 | printf("The length of all the args is %d\n, sum"); | ~^ | | | int
错误分析与修复步骤:
- fork函数未声明:fork属于POSIX API,需要包含
<unistd.h>头文件;等待子进程还需<sys/wait.h>。 - 类型不匹配:
char str;是单个字符,而argv[i]是字符串指针,应改为char *str;(或直接用argv[i],无需额外变量)。 - printf格式错误:原语句把
sum写在字符串内部,正确写法是将sum作为第二个参数传递给printf。 - 进程逻辑错误:原代码中父、子进程直接
exit(1),导致printf无法执行;子进程的sum无法传递给父进程,需通过子进程退出状态传递计算结果,父进程等待子进程结束后提取值累加。
修正后的完整代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> int main(int argc, char **argv) { int sum = 0; int status; // 跳过argv[0](程序名),只计算输入的目标字符串长度 for (int i = 1; i < argc; i++) { int pid = fork(); if (pid < 0) { perror("fork() failed"); exit(EXIT_FAILURE); } else if (pid == 0) { // 子进程计算当前参数的长度,以退出码形式返回 int len = strlen(argv[i]); exit(len); } else { // 父进程等待子进程结束,提取退出状态中的长度值 wait(&status); if (WIFEXITED(status)) { sum += WEXITSTATUS(status); } } } printf("The length of all the args is %d\n", sum); return EXIT_SUCCESS; }
关键说明:
- 循环从
i=1开始,排除程序名本身,确保只计算输入的目标字符串。 - 子进程通过
exit(len)返回当前参数的长度,父进程用wait等待子进程结束,通过WEXITSTATUS(status)获取子进程的退出码(即长度值)并累加。 - 使用
EXIT_FAILURE和EXIT_SUCCESS替代硬编码的1和0,代码更规范。
内容的提问来源于stack exchange,提问作者mozy
相关产品推荐
相关产品推荐

