Issues with execvp() and incomplete multi-argument commandsproblem with flushing input stream CRedirecting Command-line Arguments for BootstrappingRegarding 'main(int argc, char *argv[])'Program run in child process doesn't loopC struct - cannot be definedC Split CMD ArgumentsHow to wrap command arguments with /bin/sh -c and execvpe()takes null-terminate ascii string, returns int valueC Pass arguments as void-pointer-list to imported function from LoadLibrary()Vigénere Cipher in C

I recently started my machine learning PhD and I have absolutely no idea what I'm doing

How come Arya Stark didn't burn in Game of Thrones Season 8 Episode 5

Why is vowel phonology represented in a trapezoid instead of a square?

Working hours and productivity expectations for game artists and programmers

Canadian citizen who is presently in litigation with a US-based company

Given 0s on Assignments with suspected and dismissed cheating?

What technology would Dwarves need to forge titanium?

Cycling to work - 30mile return

Cannot remove door knob -- totally inaccessible!

Is there any deeper thematic meaning to the white horse that Arya finds in The Bells (S08E05)?

What kind of environment would favor hermaphroditism in a sentient species over regular, old sexes?

How does this piece of code determine array size without using sizeof( )?

Why do galaxies collide?

Roman Numerals Equation 2

Is it standard for US-based universities to consider the ethnicity of an applicant during PhD admissions?

Usage of the relative pronoun "dont"

Why do academics prefer Mac/Linux?

Why is so much ransomware breakable?

Five Powers of Fives Produce Unique Pandigital Number...Solve for X..Tell me Y

History of the Frobenius Endomorphism?

How to continually and organically let my readers know what time it is in my story?

Divisor Rich and Poor Numbers

Was the dragon prowess intentionally downplayed in S08E04?

Why does the U.S military use mercenaries?



Issues with execvp() and incomplete multi-argument commands


problem with flushing input stream CRedirecting Command-line Arguments for BootstrappingRegarding 'main(int argc, char *argv[])'Program run in child process doesn't loopC struct - cannot be definedC Split CMD ArgumentsHow to wrap command arguments with /bin/sh -c and execvpe()takes null-terminate ascii string, returns int valueC Pass arguments as void-pointer-list to imported function from LoadLibrary()Vigénere Cipher in C






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm using execvp() to run some system calls. Program works great for valid commands, and fails for any command that doesn't exist, which is perfect.
The program is, when I use execvp() on a command that needs extra arguments(like cat) and I don't provide arguments, the program just infinitely reads from input.



I'm not sure how to get around this issue, as I don't know how to 'tell' if a command is incomplete. Any ideas?



#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[])
char command[1000];


printf("Enter command: ");
scanf("%[^n]s", command);

char *temp = strtok(command, " ");
char *commandList[100];
int index = 0;

while (temp != NULL)
commandList[index] = temp;
index++;

temp = strtok(NULL, " ");


commandList[index] = NULL;

execvp(commandList[0], commandList);

printf("Failed");



The ideal result would be a print of "Command incomplete" and the process ending.










share|improve this question

















  • 1





    If the program you are starting never needs to read from stdin, why don't you just close it before execvp()?

    – EOF
    Mar 23 at 16:37











  • The common way to avoid commands from reading from stdin is to open STDIN_FILENO to /dev/null

    – Antti Haapala
    Mar 23 at 16:40











  • @EOF — one reason for not simply closing standard input is that programs are entitled to assume that standard input, standard output and standard error are opened appropriately. Redirecting standard input so it comes from /dev/null is a much better idea than simply closing standard input.

    – Jonathan Leffler
    Mar 23 at 21:31












  • Note that cat does not require any extra arguments; when it is invoked with no arguments, it reads up to EOF on standard input. It is working exactly as designed. It would be best to report errors on stderr instead of stdout; it would be best to include the failed command name in the error message (in case it wasn't what the user thought they typed); it would be best to finish the error message with a newline (fprintf(stderr, "Failed (%s)n", commandList[0]);).

    – Jonathan Leffler
    Mar 23 at 21:33












  • Oh, and when a program fails, it should exit or return a non-zero exit code (either EXIT_FAILURE from <stdlib.h>, or conventionally 1). That lets the calling code (shell or whatever) know it was not successful.

    – Jonathan Leffler
    Mar 23 at 21:43

















0















I'm using execvp() to run some system calls. Program works great for valid commands, and fails for any command that doesn't exist, which is perfect.
The program is, when I use execvp() on a command that needs extra arguments(like cat) and I don't provide arguments, the program just infinitely reads from input.



I'm not sure how to get around this issue, as I don't know how to 'tell' if a command is incomplete. Any ideas?



#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[])
char command[1000];


printf("Enter command: ");
scanf("%[^n]s", command);

char *temp = strtok(command, " ");
char *commandList[100];
int index = 0;

while (temp != NULL)
commandList[index] = temp;
index++;

temp = strtok(NULL, " ");


commandList[index] = NULL;

execvp(commandList[0], commandList);

printf("Failed");



The ideal result would be a print of "Command incomplete" and the process ending.










share|improve this question

















  • 1





    If the program you are starting never needs to read from stdin, why don't you just close it before execvp()?

    – EOF
    Mar 23 at 16:37











  • The common way to avoid commands from reading from stdin is to open STDIN_FILENO to /dev/null

    – Antti Haapala
    Mar 23 at 16:40











  • @EOF — one reason for not simply closing standard input is that programs are entitled to assume that standard input, standard output and standard error are opened appropriately. Redirecting standard input so it comes from /dev/null is a much better idea than simply closing standard input.

    – Jonathan Leffler
    Mar 23 at 21:31












  • Note that cat does not require any extra arguments; when it is invoked with no arguments, it reads up to EOF on standard input. It is working exactly as designed. It would be best to report errors on stderr instead of stdout; it would be best to include the failed command name in the error message (in case it wasn't what the user thought they typed); it would be best to finish the error message with a newline (fprintf(stderr, "Failed (%s)n", commandList[0]);).

    – Jonathan Leffler
    Mar 23 at 21:33












  • Oh, and when a program fails, it should exit or return a non-zero exit code (either EXIT_FAILURE from <stdlib.h>, or conventionally 1). That lets the calling code (shell or whatever) know it was not successful.

    – Jonathan Leffler
    Mar 23 at 21:43













0












0








0








I'm using execvp() to run some system calls. Program works great for valid commands, and fails for any command that doesn't exist, which is perfect.
The program is, when I use execvp() on a command that needs extra arguments(like cat) and I don't provide arguments, the program just infinitely reads from input.



I'm not sure how to get around this issue, as I don't know how to 'tell' if a command is incomplete. Any ideas?



#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[])
char command[1000];


printf("Enter command: ");
scanf("%[^n]s", command);

char *temp = strtok(command, " ");
char *commandList[100];
int index = 0;

while (temp != NULL)
commandList[index] = temp;
index++;

temp = strtok(NULL, " ");


commandList[index] = NULL;

execvp(commandList[0], commandList);

printf("Failed");



The ideal result would be a print of "Command incomplete" and the process ending.










share|improve this question














I'm using execvp() to run some system calls. Program works great for valid commands, and fails for any command that doesn't exist, which is perfect.
The program is, when I use execvp() on a command that needs extra arguments(like cat) and I don't provide arguments, the program just infinitely reads from input.



I'm not sure how to get around this issue, as I don't know how to 'tell' if a command is incomplete. Any ideas?



#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[])
char command[1000];


printf("Enter command: ");
scanf("%[^n]s", command);

char *temp = strtok(command, " ");
char *commandList[100];
int index = 0;

while (temp != NULL)
commandList[index] = temp;
index++;

temp = strtok(NULL, " ");


commandList[index] = NULL;

execvp(commandList[0], commandList);

printf("Failed");



The ideal result would be a print of "Command incomplete" and the process ending.







c exec system-calls






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 16:34









FlacarileFlacarile

111




111







  • 1





    If the program you are starting never needs to read from stdin, why don't you just close it before execvp()?

    – EOF
    Mar 23 at 16:37











  • The common way to avoid commands from reading from stdin is to open STDIN_FILENO to /dev/null

    – Antti Haapala
    Mar 23 at 16:40











  • @EOF — one reason for not simply closing standard input is that programs are entitled to assume that standard input, standard output and standard error are opened appropriately. Redirecting standard input so it comes from /dev/null is a much better idea than simply closing standard input.

    – Jonathan Leffler
    Mar 23 at 21:31












  • Note that cat does not require any extra arguments; when it is invoked with no arguments, it reads up to EOF on standard input. It is working exactly as designed. It would be best to report errors on stderr instead of stdout; it would be best to include the failed command name in the error message (in case it wasn't what the user thought they typed); it would be best to finish the error message with a newline (fprintf(stderr, "Failed (%s)n", commandList[0]);).

    – Jonathan Leffler
    Mar 23 at 21:33












  • Oh, and when a program fails, it should exit or return a non-zero exit code (either EXIT_FAILURE from <stdlib.h>, or conventionally 1). That lets the calling code (shell or whatever) know it was not successful.

    – Jonathan Leffler
    Mar 23 at 21:43












  • 1





    If the program you are starting never needs to read from stdin, why don't you just close it before execvp()?

    – EOF
    Mar 23 at 16:37











  • The common way to avoid commands from reading from stdin is to open STDIN_FILENO to /dev/null

    – Antti Haapala
    Mar 23 at 16:40











  • @EOF — one reason for not simply closing standard input is that programs are entitled to assume that standard input, standard output and standard error are opened appropriately. Redirecting standard input so it comes from /dev/null is a much better idea than simply closing standard input.

    – Jonathan Leffler
    Mar 23 at 21:31












  • Note that cat does not require any extra arguments; when it is invoked with no arguments, it reads up to EOF on standard input. It is working exactly as designed. It would be best to report errors on stderr instead of stdout; it would be best to include the failed command name in the error message (in case it wasn't what the user thought they typed); it would be best to finish the error message with a newline (fprintf(stderr, "Failed (%s)n", commandList[0]);).

    – Jonathan Leffler
    Mar 23 at 21:33












  • Oh, and when a program fails, it should exit or return a non-zero exit code (either EXIT_FAILURE from <stdlib.h>, or conventionally 1). That lets the calling code (shell or whatever) know it was not successful.

    – Jonathan Leffler
    Mar 23 at 21:43







1




1





If the program you are starting never needs to read from stdin, why don't you just close it before execvp()?

– EOF
Mar 23 at 16:37





If the program you are starting never needs to read from stdin, why don't you just close it before execvp()?

– EOF
Mar 23 at 16:37













The common way to avoid commands from reading from stdin is to open STDIN_FILENO to /dev/null

– Antti Haapala
Mar 23 at 16:40





The common way to avoid commands from reading from stdin is to open STDIN_FILENO to /dev/null

– Antti Haapala
Mar 23 at 16:40













@EOF — one reason for not simply closing standard input is that programs are entitled to assume that standard input, standard output and standard error are opened appropriately. Redirecting standard input so it comes from /dev/null is a much better idea than simply closing standard input.

– Jonathan Leffler
Mar 23 at 21:31






@EOF — one reason for not simply closing standard input is that programs are entitled to assume that standard input, standard output and standard error are opened appropriately. Redirecting standard input so it comes from /dev/null is a much better idea than simply closing standard input.

– Jonathan Leffler
Mar 23 at 21:31














Note that cat does not require any extra arguments; when it is invoked with no arguments, it reads up to EOF on standard input. It is working exactly as designed. It would be best to report errors on stderr instead of stdout; it would be best to include the failed command name in the error message (in case it wasn't what the user thought they typed); it would be best to finish the error message with a newline (fprintf(stderr, "Failed (%s)n", commandList[0]);).

– Jonathan Leffler
Mar 23 at 21:33






Note that cat does not require any extra arguments; when it is invoked with no arguments, it reads up to EOF on standard input. It is working exactly as designed. It would be best to report errors on stderr instead of stdout; it would be best to include the failed command name in the error message (in case it wasn't what the user thought they typed); it would be best to finish the error message with a newline (fprintf(stderr, "Failed (%s)n", commandList[0]);).

– Jonathan Leffler
Mar 23 at 21:33














Oh, and when a program fails, it should exit or return a non-zero exit code (either EXIT_FAILURE from <stdlib.h>, or conventionally 1). That lets the calling code (shell or whatever) know it was not successful.

– Jonathan Leffler
Mar 23 at 21:43





Oh, and when a program fails, it should exit or return a non-zero exit code (either EXIT_FAILURE from <stdlib.h>, or conventionally 1). That lets the calling code (shell or whatever) know it was not successful.

– Jonathan Leffler
Mar 23 at 21:43












1 Answer
1






active

oldest

votes


















0














One of the ideas from the comment completely answered my question (To the exact needs I had). Not sure how to give him credit on here, though.



The solution is to simply close stdin right before I use execvp(). If the command is not completed on the first scanf, the program throws an error, which is perfect.
Since I'm running the main program I'm using this on in a loop, I can use dup and dup2 to save and reload stdin later.



The code I used to test if it'll work:



#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[])
char command[1000];

int stdinput = dup(STDIN_FILENO);

close(STDIN_FILENO);

dup2(stdinput, STDIN_FILENO);


printf("Enter command: ");
scanf("%[^n]s", command);


printf("%sn", command);






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55315939%2fissues-with-execvp-and-incomplete-multi-argument-commands%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    One of the ideas from the comment completely answered my question (To the exact needs I had). Not sure how to give him credit on here, though.



    The solution is to simply close stdin right before I use execvp(). If the command is not completed on the first scanf, the program throws an error, which is perfect.
    Since I'm running the main program I'm using this on in a loop, I can use dup and dup2 to save and reload stdin later.



    The code I used to test if it'll work:



    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <fcntl.h>
    #include <unistd.h>

    int main(int argc, char* argv[])
    char command[1000];

    int stdinput = dup(STDIN_FILENO);

    close(STDIN_FILENO);

    dup2(stdinput, STDIN_FILENO);


    printf("Enter command: ");
    scanf("%[^n]s", command);


    printf("%sn", command);






    share|improve this answer



























      0














      One of the ideas from the comment completely answered my question (To the exact needs I had). Not sure how to give him credit on here, though.



      The solution is to simply close stdin right before I use execvp(). If the command is not completed on the first scanf, the program throws an error, which is perfect.
      Since I'm running the main program I'm using this on in a loop, I can use dup and dup2 to save and reload stdin later.



      The code I used to test if it'll work:



      #include <stdlib.h>
      #include <stdio.h>
      #include <string.h>
      #include <fcntl.h>
      #include <unistd.h>

      int main(int argc, char* argv[])
      char command[1000];

      int stdinput = dup(STDIN_FILENO);

      close(STDIN_FILENO);

      dup2(stdinput, STDIN_FILENO);


      printf("Enter command: ");
      scanf("%[^n]s", command);


      printf("%sn", command);






      share|improve this answer

























        0












        0








        0







        One of the ideas from the comment completely answered my question (To the exact needs I had). Not sure how to give him credit on here, though.



        The solution is to simply close stdin right before I use execvp(). If the command is not completed on the first scanf, the program throws an error, which is perfect.
        Since I'm running the main program I'm using this on in a loop, I can use dup and dup2 to save and reload stdin later.



        The code I used to test if it'll work:



        #include <stdlib.h>
        #include <stdio.h>
        #include <string.h>
        #include <fcntl.h>
        #include <unistd.h>

        int main(int argc, char* argv[])
        char command[1000];

        int stdinput = dup(STDIN_FILENO);

        close(STDIN_FILENO);

        dup2(stdinput, STDIN_FILENO);


        printf("Enter command: ");
        scanf("%[^n]s", command);


        printf("%sn", command);






        share|improve this answer













        One of the ideas from the comment completely answered my question (To the exact needs I had). Not sure how to give him credit on here, though.



        The solution is to simply close stdin right before I use execvp(). If the command is not completed on the first scanf, the program throws an error, which is perfect.
        Since I'm running the main program I'm using this on in a loop, I can use dup and dup2 to save and reload stdin later.



        The code I used to test if it'll work:



        #include <stdlib.h>
        #include <stdio.h>
        #include <string.h>
        #include <fcntl.h>
        #include <unistd.h>

        int main(int argc, char* argv[])
        char command[1000];

        int stdinput = dup(STDIN_FILENO);

        close(STDIN_FILENO);

        dup2(stdinput, STDIN_FILENO);


        printf("Enter command: ");
        scanf("%[^n]s", command);


        printf("%sn", command);







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 23 at 16:47









        FlacarileFlacarile

        111




        111





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55315939%2fissues-with-execvp-and-incomplete-multi-argument-commands%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현