0

I have been having issues getting execl to work.

pid_t pid = fork();

if(pid<0) {
perror("fork error\n");

} else if( pid== 0){
execl("/home/"user name"/opSys", "ps", ">>", "test.txt", (char*)NULL);

} else  {

int returnStatus;
waitpid(pid, &returnStatus, 0);

}

I am attempting to get it to run the command and then output to my text file, however nothing happens. I have been googling and trying what i find, such as different exec's. I have tried execlp(), I have tried to just get it to use ps ant not put it into a file.

I do apologize if this has been answered, which I am sure it has, however I cant find a solution that is working for me. Thanks in advance.

lostknight
  • 109
  • 6

1 Answers1

1

I assume that the >> in your command is supposed to create a redirection of the output. This, however, is not the case here. When given on the command line, the operator >> is interpreted by the shell; the command only gets the arguments up to and excluding it. The shell then takes care that the file descriptors are mangled properly for the redirection.

In your case, the command will get three arguments, namely the given strings ps, >>, and test.txt. This is like typing

 command ps '>>' test.txt

The command you are calling probably does not do very much then, maybe give an error message on stderr about the bad arguments it received (which you probably missed).

I propose you try to call a shell to help you interpret your command and pass your command as a string:

execl("/bin/sh", "-c", "/home/"user name"/opSys ps >> test.txt",
    (char*)NULL);
Alfe
  • 56,346
  • 20
  • 107
  • 159
  • Btw, I hope your `user` and `name` are some macros evaluating to strings without spaces, otherwise this is another problem and you will have to place single quotes around the path to escape the spaces: `"'/home/"user name"/opSys' ps >> test.txt"`. – Alfe Feb 14 '17 at 22:48
  • Thank you very much Alfe, this solved my issue. I had to do execl("/bin/sh", "sh"....); first but my issue is fixed. – lostknight Feb 14 '17 at 23:42