execl调用子程序失败问题求助:附调用端与被调用端代码
Hey, let's work through this issue step by step. There are a few key mistakes in your code that are preventing the hello program from launching properly or running as expected:
1. Incorrect executable path in execl
The first argument to execl needs to be the full or relative path to your executable. If you only pass "hello", the system will search for it in directories listed in your PATH environment variable—and by default, the current working directory (.) isn't always included there. This means the system might fail to locate your hello executable entirely.
Fix: Use ./hello instead of "hello" to explicitly point to the executable in your current working directory.
2. Malformed argument list in execl + type error in caller's main
- The second parameter to
execlshould be the value ofargv[0]for the launched program (usually the program's name). You passed" "(a space), which breaks the argument list passed tohello. - Your calling program's
mainfunction has a critical type error:argvshould bechar *argv[](orchar **argv), notint *argv[]. This leads to undefined behavior when you try to printargv[0].
Fix: Correct the argv type in the caller, pass the program name as the second execl argument, and add error checking to debug launch failures:
if (execl("./hello", "hello", "Hello", "World!", NULL) == -1) { perror("execl failed"); // Prints why the launch failed }
3. Broken loop logic in hello
Your while loop checks argv[i++] != NULL, then tries to print argv[i]. This skips the first argument ("Hello"), and eventually accesses memory beyond the end of the argv array when i passes the final NULL pointer—this is undefined behavior (it might crash or print garbage).
Fix: Check argv[i] != NULL first, print the valid argument, then increment i:
while (argv[i] != NULL) { printf("%s ", argv[i]); i++; }
Corrected Code
Calling Program (caller.c):
#include <stdio.h> #include <unistd.h> #include <errno.h> int main(int argc, char *argv[]) { printf("Program %s executes\n", argv[0]); // Add error checking to catch launch failures if (execl("./hello", "hello", "Hello", "World!", NULL) == -1) { perror("execl failed"); } return 0; }
Hello Program (hello.c):
#include <stdio.h> int main(int argc, char *argv[]) { int i = 1; printf("%s\n", argv[0]); printf("Program started and got string : "); while (argv[i] != NULL) { printf("%s ", argv[i]); i++; } printf("\n"); return 0; }
How to Test:
- Compile both programs:
gcc caller.c -o caller gcc hello.c -o hello - Run the caller:
./caller
You should see output like this:
Program ./caller executes hello Program started and got string : Hello World!
内容的提问来源于stack exchange,提问作者Tomas

