首页 > 解决方案 > 相同的程序在 C 中有效,但在 C++ 中无效(使用 linux 系统调用)

问题描述

我应该为学校的 linux 编写一个(非常基本的)shell。目前我只是试图用它执行一个程序(通过fork和execv),并且只计划稍后添加用户输入。我开始用 C 编写(我根本不知道/只知道它与 C++ 共享的一些部分),因为幻灯片正在使用它,但我们可以使用 C 或 C++,我计划一开始就使用 C++了解了 C 如何处理/不处理输入/输出/字符串。(我从教授的幻灯片中提取了部分代码(主要是使用状态、fork、execv 和 wait 的行)并自己添加了部分代码。)
然而,目前在使用 C 时,程序编译、运行并且似乎显示了预期的输出(通过调用 echo 函数打印出“testdesecho”)。但是当将相同的代码复制粘贴到 C++ 并尝试编译它时,我得到了几个错误(不仅仅是警告),因此甚至无法编译代码。

这是代码

//#include <iostream>

#include <stdio.h>
#include <stdlib.h>

#include <stdio.h>  
#include <ctype.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
//#include <unistd.h> 
/*
readparsefunc() {

}
*/


int main() {
    int childPid;

    int status;
    char befehlstr[20] = "/bin/echo";                                                   //location              
    char* parameterstr[61] = { "echo", "testdesecho" };                                 //argv


    childPid = fork();

    //befehlstr = "";                                       
    //parameterstr = " ";
    //cout << parameterstr[1];
    printf("%d", childPid);     printf("<- childPid(test) \n");
    printf(befehlstr);          printf("<- befehlstr(test) \n");
    printf(*parameterstr);      printf("<- parameterstr(test) \n");

    if (childPid == -1) { printf("Konnte keinen neuen Prozess erstellen"); }            
    else if (childPid == 0) {                           
        printf("child process \n");

        int testintueberlagerung = 0;
        testintueberlagerung = execv(befehlstr, parameterstr);
        if (testintueberlagerung != 0) {
            printf("%d" "<- testueberlagerungswert \n", testintueberlagerung);
        }
        //execv(befehlstr, parameterstr);                   

        exit(0);                                        
    }
    else if (childPid > 0) {
        printf("parent process \n");
        wait(&status);                                  
        printf("parent process beendet sich nun auch \n");
    }

    /*
    while (1 != 0) {

    }
    */





    return 0;
}

这些是错误:

testmitcanders.cpp:27:13: error: ‘fork’ was not declared in this scope
  childPid = fork();
             ^~~~
testmitcanders.cpp:41:26: error: ‘execv’ was not declared in this scope
   testintueberlagerung = execv(befehlstr, parameterstr);
                          ^~~~~
testmitcanders.cpp:51:3: error: ‘wait’ was not declared in this scope
   wait(&status);        
   ^~~~
testmitcanders.cpp:51:3: note: suggested alternative: ‘main’
   wait(&status);        
   ^~~~
   main

据我了解,这些都与系统调用有关,我不明白为什么需要在 C++ 中声明它们。但不是在C?(如果必须,如何声明它们?)

谢谢你的帮助

标签: c++clinuxsystem-calls

解决方案


旧版本的 C(大多数编译器仍默认支持)具有未声明函数的默认类型的概念。如果函数在声明之前使用,C 假定函数的类型是int (*)(),即接受未知数量的参数并返回 的函数int。所讨论的函数的实际类型或多或少与该定义兼容,因此它似乎有效。

另一方面,C++ 没有未声明函数的默认类型,因此在使用未声明的函数时会立即引发错误。

对于你需要的forkexec功能#include <unistd.h>,对于wait你需要#include <sys/types.h>#include <sys/wait.h>


推荐阅读