产生儿童和执行 - 未定义的行为

时间:2016-12-16 23:26:01

标签: c++ fork exec

我做了一个非常简单的程序,调用分叉并调用另一个问题。虽然它做了我想要的,但是发生了一个错误,并且cout发生了两次for循环。这是代码: main.cpp

`#include <iostream>
#include <cstdlib>

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ipc.h>

using namespace std;

char *Strduplicate(const char *source) {
    char *dest = (char *) malloc(strlen(source) + 1); // +1 = '\0'
    if (dest == NULL)
        return NULL;
    strcpy(dest, source);
    return dest;
}

string Get_cwd(string word) {
    char cwd[256];
    getcwd(cwd, sizeof(cwd));
    strcat(cwd,"/");
    strcat(cwd,word.c_str());
    string returnVal(cwd);
    return returnVal;
}

void Call_exec(const char *name,int value) {
    char *exec_array[3];
    exec_array[0] = Strduplicate(name);
    exec_array[1] = (char *)malloc(2);
    exec_array[1] = (char *)"-m";
    asprintf(&(exec_array[2]), "%d", value);
    for (int i = 0 ; i < 3; i++)
        cout << exec_array[i] << " ";
    cout << endl;
    execv(exec_array[0],exec_array);
}

int main(int argc ,char **argv) {
    srand(time(NULL));
    /* Getting arguments */
    //........
    /* Spawning children */
    for (int i = 0 ; i < 3 ; i++ ) {
        int value = rand()%100 + 1;
        pid_t waiterpid = fork();
        if (waiterpid < 0)
            cout << "ERROR FORK" << endl;
        else if (!waiterpid) {
            string program_name = Get_cwd("child");
            Call_exec(program_name.c_str(),value);
        }
    }
    return EXIT_SUCCESS;
}
`

,另一个进程是child.cpp

    #include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

using namespace std;

int main(int argc ,char **argv) {
    cout << "Child #" << getpid() << " has started" << endl;
    int value;
    /* Getting arguments */
    if (argc != 3) {
        cerr << "ERROR : Wrong arguments" << endl;
        exit(EXIT_FAILURE);
    }
    else {
        if (strncmp(argv[1],"-m",2) == 0)
            value = atoi(argv[2]);
    }
    cout << "Child has " << value << endl;
    return EXIT_SUCCESS;
}

输出

mypath/child -m 31 
mypath/child -m 23 
mypath/child -m 48 
mypath/child -m 23 
mypath/child -m 48 
alex@alex$ Child #13063 has started
Child #13062 has started
Child has 48
Child has 23
mypath/child -m 48 
Child #13064 has started
Child has 48

那么我在这里误解了什么?

1 个答案:

答案 0 :(得分:1)

这里误解的是编写现代C ++代码的一般原则。没有理由使用这些看起来很糟糕的C风格动态内存分配。使用容器可以更清洁地完成这里所做的一切,结果代码至少要小三倍。

哦,execv的参数数组必须用NULL指针终止。它不是,因此导致未定义的行为。最有可能的是,由于这个垃圾参数,execv系统调用失败 - 根据我对其手册页的细读,最有可能使用EFAULT

因此,execv()实际上在子进程中返回。由于显示的代码无法检查其返回值:子进程随机地从execv()返回后继续执行,返回到子进程中的main(),并继续自己的快乐 - 外部for循环的循环,因此导致重复输出。