你如何在 C 中生成另一个进程? [英] How do you spawn another process in C?

查看:24
本文介绍了你如何在 C 中生成另一个进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何运行外部程序并使用 C 向其传递命令行参数?如果您必须使用操作系统 API,请提供适用于 Windows、Mac 和 Linux 的解决方案.

解决方案

这真的取决于你想要做什么,确切地说,因为它是:

  1. 依赖于操作系统
  2. 不太清楚您要做什么.

不过,我会尽量提供一些信息供您决定.
在 UNIX 上,fork() 从您调用 fork 的位置创建您的进程的克隆.意思是,如果我有以下过程:

#include #include int main(){printf( "嗨 2 u
" );int mypid = fork();if( 0 == mypid )printf( "笑孩子
");别的printf( "大声笑父母
");返回( 0 );}

输出将如下所示:

<块引用><块引用>

嗨 2 u
大声笑孩子
大声笑的父母

当你fork()时,子进程返回的pid为0,父进程返回的pid就是子进程的pid.请注意,父级仅打印一次hi2u".

execve() 及其系列函数几乎总是与 fork() 一起使用. execve() 等覆盖当前带有您传递给它的应用程序名称的堆栈帧.execve() 几乎总是与 fork() 一起使用,在那里你 fork 一个子进程,如果你是父进程,你可以做任何你需要继续做的事情,如果你'重新执行一个新进程的孩子.execve() 也几乎总是与 waitpid() 一起使用——waitpid 获取子进程的 pid,从字面上看,等待直到孩子终止并将孩子的退出状态返回给您.

使用这些信息,您应该能够编写一个非常基本的 shell;一种在命令行上获取进程名称并运行您告诉它的进程.当然,shell 做的远不止这些,比如管道输入和输出,但是你应该能够使用 fork()execve() 来完成基础知识waitpid().

注意:这是 *nix 特定的!这不适用于 Windows.

希望这有帮助.

How do you run an external program and pass it command line parameters using C? If you have to use operating system API, include a solution for Windows, Mac, and Linux.

解决方案

It really depends on what you're trying to do, exactly, as it's:

  1. OS dependent
  2. Not quite clear what you're trying to do.

Nevertheless, I'll try to provide some information for you to decide.
On UNIX, fork() creates a clone of your process from the place where you called fork. Meaning, if I have the following process:

#include <unistd.h>
#include <stdio.h>

int main()
{
    printf( "hi 2 u
" );
    int mypid = fork();

    if( 0 == mypid )
        printf( "lol child
" );
    else
        printf( "lol parent
" );

    return( 0 );
}

The output will look as follows:

hi 2 u
lol child
lol parent

When you fork() the pid returned in the child is 0, and the pid returned in the parent is the child's pid. Notice that "hi2u" is only printed once... by the parent.

execve() and its family of functions are almost always used with fork(). execve() and the like overwrite the current stackframe with the name of the application you pass to it. execve() is almost always used with fork() where you fork a child process and if you're the parent you do whatever you need to keep doing and if you're the child you exec a new process. execve() is also almost always used with waitpid() -- waitpid takes a pid of a child process and, quite literally, waits until the child terminates and returns the child's exit status to you.

Using this information, you should be able to write a very basic shell; one that takes process names on the command line and runs processes you tell it to. Of course, shells do more than that, like piping input and output, but you should be able to accomplish the basics using fork(), execve() and waitpid().

NOTE: This is *nix specific! This will NOT work on Windows.

Hope this helped.

这篇关于你如何在 C 中生成另一个进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆