2

我在 C 中运行子进程,我想暂停然后运行同一个子进程。不太确定如何更好地描述我的问题,因为我是新手,但这里有一个镜头。

所以我知道你可以在另一个进程退出后使用waitpid. 但是,如果我正在等待的进程在创建等待的进程时不存在怎么办。因此,在这种情况下,我正在考虑暂停执行等待的进程,当创建等待的进程然后完成时,它将调用执行等待的进程再次运行。那么你会怎么做呢?同样,我对此并不熟悉,所以我不知道这是否是正确的方法。

编辑:我想要做什么

我正在使用子进程execvp()并行运行命令,所以如果我有一个序列sleep 1; sleep 1;,总睡眠时间将为 1 秒。但是,在某些情况下,我尝试并行echo blah > file; cat < file;,在这种情况下,我假设在将blah 输入cat文件后读取文件。echo因此,我必须等待echo完成才能完成cat。对此有更多细节,但通常假设对于任何具有文件输出的命令,必须由稍后在脚本中读取文件的任何命令等待。

4

2 回答 2

1

在 Linux 中:您可以alarm()在您之前设置一个,waitpid()这样您就可以在一定秒数后唤醒并waitpid()应该返回 EINTR,这样您就可以了解情况并杀死行为不端的人。另一种方法是使用互斥体并在等待过程中有这样的块:

if (pthread_mutex_trylock(&mutex) {
  sleep(some seconds);
  if (pthread_mutex_trylock(&mutex) {
    kill the process
  }
}

以及被监控的过程:

入口点:

pthread_mutex_lock(&mutex);
do_stuff();
pthread_mutex_unlock(&mutex);
于 2012-02-03T20:43:00.373 回答
0

Any application (process) can only wait with waitpid() on its own direct children. It can't wait on grandchildren or more distant descendants, and it can wait on neither siblings nor ancestors nor on unrelated processes.

If your application is single-threaded, you can't wait on a process that will be created after the waitpid() call starts because there is nothing to do the necessary fork() to create the child.

In a multi-threaded process, you could have one thread waiting for dying children and another thread could be creating the children. For example, you could then have the waitpid() call in thread 1 start at time T0, then have thread 2 create a child at T1 (T1 > T0), and then the child dies at T2, and the waitpid() would pick up the corpse of the child at T3, even though the child was created after the waitpid() started.

Your higher level problem is probably not completely tractable. You can't tell which processes are accessing a given file just by inspecting the command lines in a 'shell script'. You can see those that probably are using it (because the file name appears on the command line); but there may be other processes that have the name hardwired into them and you can't see that by inspecting the command line.

于 2012-02-03T21:04:09.697 回答