The system("ls") function needs to be added to the string. If done through sprintf(str, "%s", system("ls")) , then the program crashes. How can I draw a function from a string?

2 answers 2

the return of the system function is the exit code of the program called and this is an integer In your case, the termination code will be 0. Displaying a string with the address 0 (NULL) will naturally cause an error. To get the result, use int pipe (int pipefd [2]) and read from the standard input of this 'pipe' (pipefd [0])

  #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int main(int argc, char *argv[]) { int pipefd[2]; pid_t cpid; char buf; if (argc != 2) { fprintf(stderr, "Usage: %s <string>\n", argv[0]); exit(EXIT_FAILURE); } if (pipe(pipefd) == -1) { perror("pipe"); exit(EXIT_FAILURE); } cpid = fork(); if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); } if (cpid == 0) { /* Child reads from pipe */ close(pipefd[1]); /* Close unused write end */ while (read(pipefd[0], &buf, 1) > 0) write(STDOUT_FILENO, &buf, 1); write(STDOUT_FILENO, "\n", 1); close(pipefd[0]); _exit(EXIT_SUCCESS); } else { /* Parent writes argv[1] to pipe */ close(pipefd[0]); /* Close unused read end */ write(pipefd[1], argv[1], strlen(argv[1])); close(pipefd[1]); /* Reader will see EOF */ wait(NULL); /* Wait for child */ exit(EXIT_SUCCESS); } } 
  • I did not understand. Can you please a small example - FiLCh
  • put code example above - maint
  • fork () without exec () is a bad idea. - 0andriy
  • This is an excerpt from man. Any other objections? - maint

Everything is easier. It is necessary to do this:

 #include <stdio.h> int main(int argc, char *argv[]) { FILE * ff; char buf[1024]; ff = popen("ls", "r"); if (ff == NULL) { perror("popen"); return -1; } while (fgets(buf, 1024, ff) ) { printf("%s", buf); } } 

popen sends the output of the command that it executes through the channel it opens.

  • If you do this, then it displays dofig left characters between file names (( - FiLCh
  • @FiLCh displays dofig left characters I do not understand - what do the "left" characters mean? I started an example of saving the output to a log file and carefully looked at it. There are only line breaks between file names. Even in the hex form I checked - there is nothing superfluous. Where and how do you run this example? - Sergey