I am trying to return a multiple line output using execlp but am unsure of the exact method to do so. I have tried
#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
int main()
{
string str = "echo ";
str += "one \n";
str += "two \n";
str += "three \n";
if(execl("/bin/sh","/bin/sh","-c",str.c_str(),(char*)NULL) == -1)
{
printf("Child Execution Failed\n");
exit(1);
}
exit(0);
return 0;
}
I basically want all of one
, two
and three
to be printed in the shell. I get the following output though
one
/bin/sh: 2: two: not found
/bin/sh: 3: three: not found
Many thanks again!
Answer: Found a simple answer:
#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
int main()
{
string str = "echo one\n";
str += "echo two\n";
str += "echo three\n";
if(execl("/bin/sh","/bin/sh","-c",str.c_str(),(char*)NULL) == -1)
{
printf("Child Execution Failed\n");
exit(1);
}
exit(0);
return 0;
}
execlp
replaces the current process that calls it with the program specified in execlp
arguments. See the man page and note:
The
exec()
family of functions replaces the current process image with a new process image.
Having a loop trying to call execlp
many times is pointless, as after the first call to execlp
, your program is no longer executing. There are ways to use execlp
in combination with fork
or one of fork's variants) that can work, but there are easier options...
Instead, use popen
to run a distinct child process and have a pipe to read its output from.
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.