简体   繁体   中英

Why restarting program with exec() doesn't work as it should?

My task was to create simple program to restarting itself via command exec(). After each call program should assign string from keyboard to global array(max 20 char) and print content of array before assignment and after it in a hex form. The problem is that in each call my output is ending after scanf(as if program starts to restarting before printing whole output). Example output:

HEX:49|4e|49|54
Type sentence:
example

HEX:49|4e|49|54
Type sentence

etc. What is interesting program is printing out correctly only after typing END.

Thanks for any help guys.

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

char global_tab[20] = { "INIT" };

int main ( int argc, char** argv )
{
    printf ( "HEX:" );
    for ( int i = 0; i < 20; i++ )
    {
        if ( !global_tab[ i ] ) break;
        if ( global_tab[ i + 1 ] ) printf ( "%0x|" , global_tab[ i ] );
        else printf ( "%0x" , global_tab[ i ] );
    }
    printf ( "\nType sentence:\n" );
    scanf ( "%s" , global_tab );
    printf ( "HEX2:" );
    for ( int i = 0; i < 20; i++ )
    {
        if ( !global_tab[ i ] ) break;
        if ( global_tab[ i + 1 ] ) printf ( "%0x|" , global_tab[ i ] );
        else printf ( "%0x" , global_tab[ i ] );
    }
    if ( !strcmp (( const char* ) global_tab , "END." )) return 0; 
    execve(argv[0], argv, NULL);

    return 0;
}

Standard output is buffered, by default. All that printf does is write data into the buffer associated with stdout . Nothing else happens until the buffer is full or a newline character is written into the buffer (if stdout is line-buffered, which it will normally be if it is directed at a terminal.

You can use setvbuf to change how stdout is buffered. (See man setvbuf for details.) Or you can force the buffer to be flushed with fflush . (See man fflush for details.) Or you can at least write a newline character, which gives you some chance that the buffer will be flushed, although that won't work if you've redirected stdout to a file or pipe. (Still, it's a good habit. You should try to always terminate your outputs with newline characters. Writing printf formats which start with a newline is a code smell.)

If you don't arrange for the stdout buffer to actually be sent, then it will disappear when you call execve . Probably that is part of what this assignment was intended to teach you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM