2

这就是我需要的:我制作了一个 C 程序,它派生了 2 个孩子:P1、P2 我还制作了一些 bash 脚本。

我需要 P1 来运行 script1.sh,需要 P2 来运行 script2.sh。目前我正在使用该功能system("script_name.sh")system("script_name &")​​使其异步,我不知道这是否是正确的选择,因为现在它们不能按我想要的方式工作。顺便提一句:

script1.sh 这样做:

# it search a word in a dictionary and write in a file the exact line in which that 
# word is in the dictionary, i.e. word="a" is in position "1" so 
# it will write "1" in the first line of file.

 while read line; 
 do 
 sleep 1
     TRASFORMATA=$( echo "$line" | tr "[:upper:]" "[:lower:]" | sed -e 's/ //g' )  
     echo "WORDS TO SEARCH IN DICTIONARY : $TRASFORMATA:" 
     WORD=$( fgrep -w -i "$TRASFORMATA" "$dictfile" )  # got from dictionary
     echo $WORD 
  if [ -z "$WORD" ]  ## if it's not in dictionary
  then
     echo "$WORD not found!" 
     echo 
  else              
     echo "Word and relative line found.........."
##### if found, it write the relative line to a file #####
     LINE1=$( fgrep -w -n "$WORD" "$dictfile" | sed s/:$WORD//g )   
     echo "$LINE1" >> "$FILE_OUTPUT"       
  fi
 done < "$FILE_INPUT"  

script2.sh 这样做:

# delete lines starting with letter 'z' FROM SAME FILE THAT USES script1.sh
sleep 1
while true;
do
sleep 2
echo "DELETING WORDS "
sed -i '/^z/d' "$FILE_OUTPUT"
done

他们在同一个文件(.txt)上工作。 我想要的是同时运行它们并且它们必须轮流工作,我的意思是在P之后!已经用它的 script1 读取了第一行,P2 必须运行它的 script2,与第二行、第三行等相同......

我怎样才能从 C 程序中做到这一点?重要的是每个进程都运行一个脚本,并且这些脚本必须并行交替执行。 通过这种方式,我达到了我的目标,即让 2 个进程一起产生一个输出,以便让三分之一的进程读取该输出并处理它!

我希望这很清楚

谢谢你的帮助

4

1 回答 1

1

交错处理进程的实际执行是非常尴尬的。

要交错输出,让每个脚本将其 STDOUT 写入管道,然后编写一个小程序,依次从每个管道读取一行,并将其写入输出。

然而,这似乎是一个很长的问题。如果两个进程确实需要同步——每个进程依次执行一个处理步骤——最简单的方法是让一个进程按顺序执行命令。并发很难——如果你不需要它就不要使用它。

于 2013-02-05T21:32:40.163 回答