简体   繁体   中英

Why does my bash script not work in my C program?

My program takes an arbitrary number of words from the user and stores them in a double pointer **stringArr . These values are then concatenated into a string which is then passed into a bash script I have.

The problem I have is that the bash script doesn't echo the command I want it to, and I am unsure why.

string = malloc(N * sizeof(char));

    for (int j = 0; j < N; j++) {
        strcat(string, stringArr[j]);
        strcat(string, " ");
    }

puts("\n\nYour input sorted in alphabetical order:");
    if (fork() == 0) {
        execl("./sortString.sh", "sortString.sh", string, NULL);
    }
#!/bin/bash
for NAME in "$@"
do
VAR=$VAR" "$NAME
done
echo $VAR | tr ’ ’ ’\n’ | sort | tr ’\n’ ’ ’

Is there something I am missing?

Note: the bash script is in the same directory as the program; the program works in regards to taking user input and it putting into the string string .

If you want to try out the bash script, an example of string I have passed through is: "one two three " (there is a space after 'three').

You cannot use the exec() family of functions to execute a shell script directly; they require the name of a proper executable. If you check the return value of your execl() call, I'm sure you'll see an error ( -1 ), and errno will probably have been set to ENOEXEC .

You could try using system() instead, but it is generally frowned upon because you'd need to build a full (single) command string, and making sure that everything is properly escaped and such is error-prone.

Instead, I'd recommend that you give "/bin/sh" or "/bin/bash" as the first argument to exec() . Then, the args to sh would need to be the path of your script, and then the args that your script will use.

(this is what your shell does automatically when you run a script; it reads the #! line, and executes "/bin/bash your-script your-args...")

Your string allocation is too small. You're allocating space for N chars, but you're strcat ing N spaces into it, plus whatever is in your stringArr (which I assume is not full of empty strings).

Even then, you will have just one big string of args, but exec() wants them separated. Think of it like if you point quotes around all the args in bash; you get just one big argument, which contains spaces.

After you fix that (so that you have an array of strings rather than just one big one), you will run into problems with execl() . It takes the arguments separately, but you're trying to send one big array of them. You'll want execv() instead, which accepts an array of strings for the argument list. Remember that the first string in that list must be your script path.

Are you sure this wouldn't be easier to do with qsort() ?

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