Find the answer to your Linux question:
Results 1 to 2 of 2
Hello, I wrote a C wrapper to execute a shell program. I used execl to call the shell script and it pass some arguments as well. Passing command line arguments ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Nov 2007
    Posts
    5

    execl and sprintf not working together


    Hello,

    I wrote a C wrapper to execute a shell program. I used execl to call the shell script and it pass some arguments as well. Passing command line arguments (using argv[]) works fine. But, I wanted to pass an integer as well.

    I will paste a sample code here. It works pretty fine in a machine with "gcc version 3.2.2 20030222 (Red Hat Linux 3.2.2-5)". But, it give segmentation fault in a machine with "gcc version 4.1.2 20070626 (Red Hat 4.1.2-13)".

    Here is a sample code:
    ----------------------
    tst.c
    ******
    #include <unistd.h>

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

    int ret, userid, fd;
    char *user_id;
    userid=getuid();
    sprintf( user_id, "%d", userid );
    printf("hi:%s\n",user_id);
    ret = execl ("tst.sh", "tst.sh", user_id ,argv[1],argv[2], argv[3], argv[4], (char*)0);
    printf("hi\n");
    if (ret==-1) {
    perror();
    printf("Error occured during exec, exiting\n");
    exit (1);
    }
    }


    tst.sh
    *******
    #! /bin/bash

    echo "first $1"
    echo "second $2"
    echo "third $3"
    echo "fourth $4"
    ------------------------------------------------------------

    Here, sprintf function looks fine and it gets printed in the next line. But, execl is not working. I tried passing user_id like "(char *)user_id, but didn't work.

    The funny thing I noticed here is, this code won't work even if you remove 'user_id' from execl statement. But, it will work if you remove sprintf() as well. As I mentioned above the same code works pretty fine in a machine with "gcc version 3.2.2 20030222 (Red Hat Linux 3.2.2-5)"

    Any ideas???.

    Regards,
    Mohammed.

  2. #2
    Just Joined!
    Join Date
    Nov 2007
    Posts
    5

    Wink yes, got it

    it got fixed. The problem was with memory allocation. I defined 'user_id' like:

    char *user_id=(char *)malloc(11);

    Now, the script is working fine.

    Regards,
    Mohammed.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •