вывод команды оболочки - функция, обратная system()

Ответить
ya
^-^
Сообщения: 2336
Зарегистрирован: 16 дек 2021, 19:56

вывод команды оболочки - функция, обратная system()

Сообщение ya »

Код: Выделить всё

#include <stdio.h>
#include <stdlib.h>
 
int main (int argc, char* argv [])
{
    FILE* pipe;
 
    char buf [BUFSIZ];
 
    if (argc != 2)
    {
    fprintf (stderr, "Usage: %s COMMAND\n", argv [0]);
    exit (1);
    }
    
    printf ("Trying to execute command `%s'\n", argv [1]);
 
    if ((pipe = popen (argv [1], "r")) == NULL)
    {
    perror (argv [1]);
    exit (1);
    }
 
    while (fgets (buf, BUFSIZ, pipe) != NULL)
    printf ("Got line: %s", buf);
 
    if (ferror (pipe))
    perror (argv [1]);
 
    pclose (pipe);
 
    exit (0);
}

Открываем пайп и читаем из него как из файла.

Код

[nameless@desktop c]$ ./sample 'ls -l'
Trying to execute command `ls -l'
Got line: итого 32
Got line: -rw-rw-r--. 1 nameless nameless 527 марта 6 20:59 main.c
Got line: -rw-rw-r--. 1 nameless nameless 854 марта 6 18:27 main.c~
Got line: -rw-rw-r--. 1 nameless nameless 6768 марта 6 20:59 main.o
Got line: -rw-rw-r--. 1 nameless nameless 302 марта 2 13:05 Makefile
Got line: -rwxrwxr-x. 1 nameless nameless 10295 марта 6 20:59 sample
[nameless@desktop c]$
ya
^-^
Сообщения: 2336
Зарегистрирован: 16 дек 2021, 19:56

Re: вывод команды оболочки - функция, обратная system()

Сообщение ya »

The following program accepts any number of command-line arguments and prints them out:

#include <stdio.h>

int main (int argc, char *argv[])
{
int count;

printf ("This program was called with \"%s\".\n",argv[0]);

if (argc > 1)
{
for (count = 1; count < argc; count++)
{
printf("argv[%d] = %s\n", count, argv[count]);
}
}
else
{
printf("The command had no other arguments.\n");
}

return 0;
}
If you name your executable fubar, and call it with the command ./fubar a b c, it will print out the following text:

This program was called with "./fubar".
argv[1] = a
argv[2] = b
argv[3] = c
Ответить