popen fails with “sh: <command>: not found”

a 夏天 提交于 2019-12-08 18:01:36

问题


I'm developing a server application and I recently encountered this wierd error on a testing server (Debian Squeeze).

Every executable I pass to popen fails with a msg:

sh: sort: not found // happens to any command

This happens regardless whether I point to the full path returned by "type" or keep it short . As mentioned earlier, this happens at only one testing environment, to add confusion, am running the same OS and had no problem whatsoever.

Popen is apparently using sh to execute commands, but if I run the same command thru the command-line (bash or sh), everything's fine

Thanks in advance

(PS: even tried Python os.popen just to nail this head scratcher, and it works!)

Edit this is a simple call that fails:

$command="tail -10 myfile";
$handle = popen($command.' 2>&1','r');
if($handle){
  while (!feof($handle)){
  ....//process buffer
  }
}

returns:

sh: tail: not found

回答1:


Probably your PATH is NOT configured properly, when calling popen. I guess this is a PHP configuration problem, but you can bypass it by:

  1. Run which tail to determine the full path to the tail program.
  2. Call popen with the path found in 1.



回答2:


I found this question while searching for my own answer regarding the exact same output. Although I am coding in C, I am still using popen(). I am a beginner in C, and discovered that I made the following mistake.

I am answering this in the hope it may be useful to others searching for the same error message. This is how I encountered, discovered, and corrected the problem.

I declared a string and concatenated other strings with it to formulate my command line.

I printed the line to stdout to verify it was the command I wanted. When copied from stdout and executed, the line worked. So why did the shell choke from popen()?

I piped the output to a file and opened the file in an editor, and saw that when my empty string was initialized, the special character '^A' was created with the string, which was not displayed on the terminal.

I changed the way I declared the char array from this:

char varname[];

to this:

char varname[512] = {""};

This resolved the issue. I would encourage anyone with a similar problem to look for hidden characters in the string used with popen().



来源:https://stackoverflow.com/questions/2717897/popen-fails-with-sh-command-not-found

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!