如果我使用 fork() 和 execv() 生成多个在后台运行的子进程,并且我想将其中一个子进程带到前台,我该怎么做?
我正在尝试编写一个可以在前台或后台启动进程的外壳程序。
我正在尝试使用系统调用进行基本的bash,但我对指针数组有一些小问题.
为了恢复我的代码,我从stdin中读取带有read()的命令到缓冲区,然后我使用strsep()将命令与参数和所有参数分离到一个数组中.然后我用fork()创建一个新进程,并使用execvp()的相关参数执行该命令.
所有这一切都进入无限循环,直到用户键入"退出"(尚未编码).问题是在第一次迭代之后,我需要*pArgs为空,用于下一个命令和参数.我不知道怎么做......
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv) {
    char bBuffer[BUFSIZ], *pArgs[10], *aPtr = NULL, *sPtr;
    int aCount;
    pid_t pid;
    while(1) {
        write(1, "\e[1;31mmyBash \e[1;32m# \e[0m", 27);
        read(0, bBuffer, BUFSIZ);
        sPtr = bBuffer;
        aCount = 0;
        do {
            aPtr = strsep(&sPtr, " ");
            pArgs[aCount++] = aPtr;
        } while(aPtr);
        pArgs[aCount-2][strlen(pArgs[aCount-2])-1] = '\0';
        // Debug code to output pArgs content
        write(1, "|>", 2);
        write(1, pArgs[0], strlen(pArgs[0]));
        write(1, "<|", 2);
        if(strlen(pArgs[0]) > 1) { …