简体   繁体   English

在Linux下从C程序运行多个C程序

[英]Running multiple C programs from a C program under Linux

I'm trying to learn a bit or 2 about process communication under Linux, so I wrote 2 simple C programs that communicate with each other. 我正在尝试在Linux下学习一些关于进程通信的内容,所以我编写了两个相互通信的简单C程序。

However, it's a bit annoying to have to run them manually every single time, so I'd like to know is there a way to make a program that will run them both, something like this: 但是,每次都必须手动运行它们有点烦人,所以我想知道是否有办法制作一个可以同时运行它们的程序,如下所示:

./runner program1 program2

I'm using latest Ubuntu and Bash shell. 我正在使用最新的Ubuntu和Bash shell。

run.sh script run.sh脚本

#!/bin/sh
./program1 & 
./program2 &

run command: 运行命令:

$sh run.sh

This line will do (in Bash): 这行会做(在Bash中):

program1 & program2 &

If you want to record the output: 如果要记录输出:

program1 >output1.txt & program2 >output.txt &

If you want to run the commands in two separate terminals: 如果要在两个单独的终端中运行命令:

xterm -e program1 & xterm -e program2 &

Why not use this: 为什么不用这个:

./program1;./program2

or 要么

./program1 &;./program2 &

I don't know why somebody thinks it's not useful,but it really works. 我不知道为什么有人认为它没用,但确实有效。

Surely you can write a script,but what's the content of the script?Still the same thing. 当然你可以写一个脚本,但脚本的内容是什么?还是一样的。

And you can change it at once with no need to open the script first. 您可以立即更改它,而无需先打开脚本。

只需编写一个shell脚本来执行您想要的操作 - 您不需要使用C程序来运行C程序。

Do do exactly what you asked, first created a file called runner which will be the shell script. 完全按照你的要求做,首先创建一个名为runner的文件,它将是shell脚本。

#!/bin/bash

for arg in $@
do
$arg & 
done

$@ in bash is an array of all the arguments passed to the script, this makes the script no restricted to only launching 2 programs. bash中的$@是传递给脚本的所有参数的数组,这使得脚本不限于仅启动2个程序。 Note any programs your launch with this scripts need to be on the $PATH or passed to the script as ./program1 . 请注意,使用此脚本启动的任何程序都必须位于 $PATH或者以./program1传递给脚本。

./runner ./program1 program2 

In the example program1 is not on the $PATH but program2 is. 在示例中, program1不在$PATH但是program2是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM