I wrote a simple test program to try to call execl(...) with the path of the find command as a test. There is no output on stdout, no matter the parameters sent to the find program. Why is this happening? Here's the program:
#include <unistd.h>
#include <sys/types.h>
#include <cstdio>
#include <cerrno>
int main(int argc, char** argv)
{
if(execl("/usr/bin/find", "/usr/bin/find", "/", "-maxdepth", "1", "-name", "bin", (char*)NULL) == -1)
{
perror("In QueryRequest::Client_Execute(): ");
_exit(1);
}
return 0;
}
Here's the compilation and run test of the program above; note that there is no output from it. Executing find from the console with the above parameters yields non-empty output. What is the problem here and how can I get past it?
[main@main-pc src]$ g++ test.cpp -o test
[main@main-pc src]$ ./test
[main@main-pc src]$
The specific meta-info about the targeted system:
Linux 4.9.66-1-MANJARO #1 SMP PREEMPT Thu Nov 30 14:08:24 UTC 2017
Using the -print argument to find does not change the outcome. The behaviour is as expected on other systems, including a 4.9.66-1-MANJARO and another ARCH-based proprietary distro using a 4.11 kernel. I've compiled it with g++ 7.2 and other 4.x versions.
the posted code does not compile, with a C compiler.
Suggest using the following code:
#include <unistd.h> // execl(), _exit()
#include <stdio.h> // perror()
int main( void )
{
execl("/usr/bin/find", "/usr/bin/find", "/", "-maxdepth", "1", "-name", "bin", NULL);
perror("In QueryRequest::Client_Execute(): ");
_exit(1);
}
Read carefully the documentation of execl(3) and of the execve(2) system call (which gets called by execl
).
Notice that execl
and execve
returns only on failure. When they are successful, they do not return (since the calling process is changing entirely its virtual address space to run the new executable ).
To debug your issue, you could temporarily replace /usr/bin/find
by /bin/echo
, and/or perhaps also use strace(1) , eg strace ./test
.
BTW, using test
as your program name is poor taste , since conflicting with the standard test(1) (eg the bash test
builtin ) .... So I strongly recommend using another name, eg mytest
....
Of course, read also carefully the documentation of find(1) .
BTW, on my Debian system your program (renamed as curious
) works and outputs /bin
Notice that you could avoid running a find
process from your C program by using nftw(3) .
Also, remember that C and C++ are different languages (and your code looks like C, but then you should #include <stdio.h>
and #include <errno.h>
). Don't forget to compile with all warnings and debug info, so with -Wall -Wextra -g
for GCC . Learn to use the debugger gdb
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.