简体   繁体   English

帮助使用C创建linux shell

[英]help with creating linux shell using C

I'm supposed to create a linux shell using C. Below is my code: 我应该使用C创建一个Linux shell。下面是我的代码:

#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define SHELL "/bin/sh"
#include "extern.h"

int mysystem (char *command)
{
  int status;
  pid_t pid;

  pid = fork ();
  if (pid == 0)
    {

      execl (SHELL, SHELL, "-c", command, NULL);
      _exit (EXIT_FAILURE);
    }
  else if (pid < 0)

    status = -1;
  else

    if (waitpid (pid, &status, 0) != pid)
      status = -1;
  return status;
}

Everything is right when I test the code using different commands like "ls", "man", etc. but when I use notepad to create a testfile containing the following: 当我使用“ ls”,“ man”等不同的命令测试代码时,一切都正确,但是当我使用记事本创建包含以下内容的测试文件时,一切都正确:

echo "hello"
exit 2

the return code come out to be 512 when it's supposed to be just 2 . 返回代码出来是512时,它应该只是2 Can anyone help me fix my code? 谁能帮我修复我的代码?

status is not the exit code; status不是退出代码; it contains other information as well. 它也包含其他信息。 Normally the return value is in bits 8-15 of status , but you should be using the macros in wait.h to extract the return value from status in a portable way. 通常,返回值位于status 8-15位中,但是您应该使用wait.h的宏以可移植的方式从status中提取返回值。

Note that 512 is 2<<8 . 注意512是2<<8

Make sure you're using the macros like WIFEXITED and WEXITSTATUS on your status value. 确保在status值上使用WIFEXITEDWEXITSTATUS类的宏。 See your operating system's man page for waitpid . 有关waitpid请参见操作系统的手册页。 Here is a description of the POSIX requirements on waitpid . 是对waitpid的POSIX要求的描述。

By notepad do you mean you're using a Windows program to create a Unix shell script? 通过记事本,您是说您正在使用Windows程序创建Unix Shell脚本吗? That doesn't work because you end up with CRLF at the end of each line instead of LF. 那是行不通的,因为您在每一行的末尾都使用CRLF而不是LF。 Try the "dos2unix" command on the script to convert it to Unix format and then run it. 在脚本上尝试“ dos2unix”命令将其转换为Unix格式,然后运行它。

I assume you're aware that code is already available in the system() library call? 我假设您知道在system()库调用中已经可以使用代码了吗? Judging by your function name, I'd guess you're just trying to learn how to do it with system calls. 从您的函数名称来看,我猜您只是在尝试学习如何通过系统调用来实现。

Try enclosing your command string you supply to /bin/sh with quotes, because otherwise the space character makes /bin/sh think you are supplying another option to the shell itself, not to the command you are calling. 尝试将提供给/bin/sh command字符串括在引号中,因为否则空格字符会使/bin/sh认为您正在为shell本身而不是正在调用的命令提供另一个选项。 For example, try this in a terminal: 例如,在终端中尝试以下操作:

/bin/sh -c exit 2
echo $?

and

/bin/sh -c "exit 2"
echo $?

The first one gives 0 , and the second one gives the desired 2 . 第一个给出0 ,第二个给出所需的2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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