linux c (2) 创建进程

翻头文件,无意发现人家早已经写的已经很detail了,于是偷了一下懒,copy了下。

创建一个新的进程,可以用exec函数族的几个函数,当然,能完成任务的不止这几个了,system,fork也都可以创建新的进程。exec函数族共有以下几个:

execl,execv,execle,execve,execlp,execvp,其中其他几个函数都是间接调用了execve。函数名中,l表示参数用的是列表,v表示用的是数组,e表示指定环境变量,p表示让系统去搜索路径。

来个例子:

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

int main()
{
    char *args[]={"/usr/bin/vim",NULL};
    printf("pid assigned by system is: %d/n",getpid());
    if(execve("/usr/bin/vim",args,NULL)<0)
        perror("error occurs when creating process/n");
    return 1;
}

调用时最好判断一下调用是否成功了。

编译了之后执行一下看看,然后查看进程状态,用grep筛选一下:

ps -ef|grep vim

可以看到vim进程启动后原进程已经结束了(看进程号)。

除了用exec族,还可以用system函数,这个函数不用包含unistd.h,不过需要stdlib.h

来个例子:

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

int main()
{
    int rt;
    printf("process id assigned by system is : %d/n",getpid());
    rt=system("ping www.baidu.com");
    return 0;
}

启动后会一直ping,按ctrl+Z结束。在ping的时候可以查看一下进程号(pid),可以发现这个ping有了一个新的pid,也就是说调用system创建的进程不会导致原来的进程结束。

ps -ef|grep ping

执行system函数隐含调用了fork,execve,waitpid函数。

 

 

头文件里没搜到作者名字,就省了,以下是关于exec函数族的详细说明:

==========================================

26.5 Executing a File
=====================

This section describes the `exec' family of functions, for executing a
file as a process image.  You can use these functions to make a child
process execute a new program after it has been forked.

   To see the effects of `exec' from the point of view of the called
program, see *note Program Basics::.

   The functions in this family differ in how you specify the arguments,
but otherwise they all do the same thing.  They are declared in the
header file `unistd.h'.

 -- Function: int execv (const char *FILENAME, char *const ARGV[])
     The `execv' function executes the file named by FILENAME as a new
     process image.

     The ARGV argument is an array of null-terminated strings that is
     used to provide a value for the `argv' argument to the `main'
     function of the program to be executed.  The last element of this
     array must be a null pointer.  By convention, the first element of
     this array is the file name of the program sans directory names.
     *Note Program Arguments::, for full details on how programs can
     access these arguments.

     The environment for the new process image is taken from the
     `environ' variable of the current process image; see *note
     Environment Variables::, for information about environments.

 -- Function: int execl (const char *FILENAME, const char *ARG0, ...)
     This is similar to `execv', but the ARGV strings are specified
     individually instead of as an array.  A null pointer must be
     passed as the last such argument.

 -- Function: int execve (const char *FILENAME, char *const ARGV[],
          char *const ENV[])
     This is similar to `execv', but permits you to specify the
     environment for the new program explicitly as the ENV argument.
     This should be an array of strings in the same format as for the
     `environ' variable; see *note Environment Access::.

 -- Function: int execle (const char *FILENAME, const char *ARG0, char
          *const ENV[], ...)
     This is similar to `execl', but permits you to specify the
     environment for the new program explicitly.  The environment
     argument is passed following the null pointer that marks the last
     ARGV argument, and should be an array of strings in the same
     format as for the `environ' variable.

 -- Function: int execvp (const char *FILENAME, char *const ARGV[])
     The `execvp' function is similar to `execv', except that it
     searches the directories listed in the `PATH' environment variable
     (*note Standard Environment::) to find the full file name of a
     file from FILENAME if FILENAME does not contain a slash.

     This function is useful for executing system utility programs,
     because it looks for them in the places that the user has chosen.
     Shells use it to run the commands that users type.

 -- Function: int execlp (const char *FILENAME, const char *ARG0, ...)
     This function is like `execl', except that it performs the same
     file name searching as the `execvp' function.

   The size of the argument list and environment list taken together
must not be greater than `ARG_MAX' bytes.  *Note General Limits::.  In
the GNU system, the size (which compares against `ARG_MAX') includes,
for each string, the number of characters in the string, plus the size
of a `char *', plus one, rounded up to a multiple of the size of a
`char *'.  Other systems may have somewhat different rules for counting.

   These functions normally don't return, since execution of a new
program causes the currently executing program to go away completely.
A value of `-1' is returned in the event of a failure.  In addition to
the usual file name errors (*note File Name Errors::), the following
`errno' error conditions are defined for these functions:

`E2BIG'
     The combined size of the new program's argument list and
     environment list is larger than `ARG_MAX' bytes.  The GNU system
     has no specific limit on the argument list size, so this error
     code cannot result, but you may get `ENOMEM' instead if the
     arguments are too big for available memory.

`ENOEXEC'
     The specified file can't be executed because it isn't in the right
     format.

`ENOMEM'
     Executing the specified file requires more storage than is
     available.

   If execution of the new file succeeds, it updates the access time
field of the file as if the file had been read.  *Note File Times::,
for more details about access times of files.

   The point at which the file is closed again is not specified, but is
at some point before the process exits or before another process image
is executed.

   Executing a new process image completely changes the contents of
memory, copying only the argument and environment strings to new
locations.  But many other attributes of the process are unchanged:

   * The process ID and the parent process ID.  *Note Process Creation
     Concepts::.

   * Session and process group membership.  *Note Concepts of Job
     Control::.

   * Real user ID and group ID, and supplementary group IDs.  *Note
     Process Persona::.

   * Pending alarms.  *Note Setting an Alarm::.

   * Current working directory and root directory.  *Note Working
     Directory::.  In the GNU system, the root directory is not copied
     when executing a setuid program; instead the system default root
     directory is used for the new program.

   * File mode creation mask.  *Note Setting Permissions::.

   * Process signal mask; see *note Process Signal Mask::.

   * Pending signals; see *note Blocking Signals::.

   * Elapsed processor time associated with the process; see *note
     Processor Time::.

   If the set-user-ID and set-group-ID mode bits of the process image
file are set, this affects the effective user ID and effective group ID
(respectively) of the process.  These concepts are discussed in detail
in *note Process Persona::.

   Signals that are set to be ignored in the existing process image are
also set to be ignored in the new process image.  All other signals are
set to the default action in the new process image.  For more
information about signals, see *note Signal Handling::.

   File descriptors open in the existing process image remain open in
the new process image, unless they have the `FD_CLOEXEC'
(close-on-exec) flag set.  The files that remain open inherit all
attributes of the open file description from the existing process image,
including file locks.  File descriptors are discussed in *note
Low-Level I/O::.

   Streams, by contrast, cannot survive through `exec' functions,
because they are located in the memory of the process itself.  The new
process image has no streams except those it creates afresh.  Each of
the streams in the pre-`exec' process image has a descriptor inside it,
and these descriptors do survive through `exec' (provided that they do
not have `FD_CLOEXEC' set).  The new process image can reconnect these
to new streams using `fdopen' (*note Descriptors and Streams::).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值