シェルが組み込みエコーではなく外部エコーのみを実行するようにする方法は?

シェルが組み込みエコーではなく外部エコーのみを実行するようにする方法は?

system()ライブラリ関数を使用するCプログラムがあります。以下はソースコードです。

#include<stdlib.h>
int main()
{ 
    //Some code
    system("echo Hello World");
    //some code
    return 0;
}    

$PATHこのCプログラムを実行する前に、代わりに /home/user1/bin/echo実行するように変更しました。/bin/echo

export PATH="/home/user1/bin"

ちなみにCプログラムを実行すると実行されません/home/user1/bin/echo

シェルがecho一つなので見つけようとしなかったからですか?shell built-inecho$PATH

それから組み込まechoれた。$PATHecho

ベストアンサー1

command機能をバイパスしますが、シェル組み込み機能はバイパスしません。最も安全な方法は、フルパスを使用することです。

system("/home/user1/bin/echo Hello world!")

そうでない場合は、exec組み込みの機能を試してください。

system("exec echo Hello World!")

たとえば、

$ cat foo.c       
#include<stdlib.h>
int main()
{ 
    //Some code
    system("exec echo --help");
    system("command echo --help");
    system("echo --help");
    //some code
    return 0;
}  
$ gcc -o foo foo.c
$ ./foo
Usage: echo [SHORT-OPTION]... [STRING]...
  or:  echo LONG-OPTION
Echo the STRING(s) to standard output.

  -n             do not output the trailing newline
  -e             enable interpretation of backslash escapes
  -E             disable interpretation of backslash escapes (default)
      --help     display this help and exit
      --version  output version information and exit

If -e is in effect, the following sequences are recognised:

  \\      backslash
  \a      alert (BEL)
  \b      backspace
  \c      produce no further output
  \e      escape
  \f      form feed
  \n      new line
  \r      carriage return
  \t      horizontal tab
  \v      vertical tab
  \0NNN   byte with octal value NNN (1 to 3 digits)
  \xHH    byte with hexadecimal value HH (1 to 2 digits)

NOTE: your shell may have its own version of echo, which usually supersedes
the version described here.  Please refer to your shell's documentation
for details about the options it supports.

Report echo bugs to [email protected]
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info coreutils 'echo invocation'
--help
--help

2番目と3番目の呼び出しは、フラグをサポートしていない組み込みsystem関数を実行します。私の場合、最初の実行はこのフラグをサポートするGNUによって提供されます。echo--help/bin/echo--help

~からman 3 system(POSIX):

The environment of the executed command shall be as if a child  process
were created using fork(), and the child process invoked the sh utility
using execl() as follows:

      execl(<shell path>, "sh", "-c", command, (char *)0);
where <shell path> is an unspecified pathname for the sh utility.

お持ちの場合Linux:

system()  executes a command specified in command by calling /bin/sh -c
command, and returns after the  command  has  been  completed.   During
execution  of  the  command,  SIGCHLD  will  be blocked, and SIGINT and
SIGQUIT will be ignored.

明示的に使用されるため、/bin/sh -c一般的な方法では影響を与えることはできません。交換できます/bin/sh。その後、ファイルドライバを使用してバブルラップを爆発させることができます。

おすすめ記事