Считать вывод команды `date` в переменную в C script Unix - PullRequest
0 голосов
/ 30 апреля 2020

Я должен сохранить то, что выводит команда date (Unix), в виде строки в переменную, а затем записать это в канал в дочернем процессе. В конце выведите это в родительский процесс, используя канал. Это то, что я пробовал до сих пор:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    int channel[2];
    if(pipe(channel) == -1) { printf("Eroare la crearea pipe ului!\n"); return 1; }

    pid_t pid = fork();
    if(pid < 0) { printf("Eroare la crearea procesului\n"); }
    else if(pid > 0)
    {
        wait(NULL);      // wait for the child to write to the pipe
        close(channel[1]); // close not-needed side of pipe

        char *aux;
        read(channel[0], aux, sizeof(channel[0]));

        printf("Sirul citit este: '%s'\n", aux);
        close(channel[0]);

    // exit(0);
    }
    else
    {
        close(channel[0]);

        // char *data_acum = (char*)system("date");
        char *data_acum = system("date");
        printf("variabila `data_acum` are valoarea '%s'\n", data_acum);
        // printf(typeof(data_acum));
        write( channel[1], data_acum, sizeof(data_acum) );
        // write( channel[1], system("date"), sizeof(system("date")) );

    // exit(0);
    }

return 0;
}

вывод :

Thu Apr 30 02:05:39 EEST 2020
variabila `data_acum` are valoarea '(null)'
Sirul citit este: '1I^HHPTLz'

Более конкретно, моя проблема:

Я пытаясь выяснить, почему эта строка char *data_acum = system("date") или комментарий //char *data_acum = (char*)system("date") не работают; "работая", я ожидаю сохранить строку, которая будет отображаться date, если я буду использовать ее непосредственно в командной строке. Разве это system("date") не возвращает строку, которую я могу сохранить в переменной type const char*?

Кроме того, я не уверен на 100%, что хочет сказать предупреждение: warning:initialization makes pointer from integer without a cast [-Wint-conversion]. Я понимаю, что между типами есть некоторая несовместимость, но действительно ли system("date") возвращает int? И, таким образом, я неправильно пытаюсь каким-то образом преобразовать его в const char*? Я помню, что видел, что даты на самом деле представляют собой шестнадцатеричные числа.

Извините за, может быть, слишком много вопросов! В итоге, чтобы подвести итог моих вопросов: что возвращает system("date") и как я могу решить мою проблему?

ожидаемый результат :

Thu Apr 30 02:05:39 EEST 2020
variabila `data_acum` are valoarea 'Thu Apr 30 02:05:39 EEST 2020'
Sirul citit este: 'Thu Apr 30 02:05:39 EEST 2020'

Примечания:

1) Я должен использовать date

2) Я специально не проверял статус возврата ребенка

3) Я знаю, что не рекомендуется использовать wait(NULL).

1 Ответ

0 голосов
/ 30 апреля 2020

Мне удалось решить мою проблему. Я искал что-то похожее на это:

#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

#define BUFFER_SIZE 105

int main()
{
    int channel[2];
    if(pipe(channel) == -1) { printf("Eroare la crearea pipe ului!\n"); return 1; }

    pid_t pid = fork();
    if(pid < 0) { printf("Eroare la crearea procesului\n"); }
    else if(pid > 0)
    {

        close(channel[1]); // close pipe's writing end
//      wait(NULL); // wait for children to finish

        int status;
        waitpid(pid, &status, 0);   // wait for children to finish
        int return_value = WEXITSTATUS(status);

        char aux[BUFFER_SIZE];
        read(channel[0], aux, BUFFER_SIZE);
        close(channel[0]); // close pipe's reading end

        printf("%s\n", aux);
    //exit(0);
    }
    else
    {
        close(channel[0]); // inchid capatul de citire al pipe ului (in copil voi scrie in pipe)

        system("date >> temp.txt"); /* I have eventually used an auxiliary file to get the output of `date`
        command into it, then read it using f.
        */

        FILE * fptr = fopen("temp.txt", "r");
        if(fptr == NULL) { printf("eroare la crearea fisierului auxiliar\n"); exit(EXIT_FAILURE); }

        char buffer[BUFFER_SIZE];
        fgets(buffer, BUFFER_SIZE, fptr); // read date

        fclose(fptr); // close file
        remove("temp.txt"); // delete temporary file

        buffer[strlen(buffer) - 1] = '\0'; // delete '\n' character from the end of read string (might need it without the '\n' later)
        write(channel[1], buffer, sizeof(buffer)); // scriu in capatul de scriere al pipe ului data citita
    exit(0); // succesfully leave child
    }

return 0;
}

Теперь я собираюсь попытаться реализовать гораздо более простой способ, используя popen; также предложено Джозефом Сибли-Восстановителем Моники.

...