Skip to content

Instantly share code, notes, and snippets.

@dyama
Last active August 29, 2015 14:18
Show Gist options
  • Save dyama/3d7f4595450ca1a07698 to your computer and use it in GitHub Desktop.
Save dyama/3d7f4595450ca1a07698 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
void heavy_function()
{
sleep(5);
}
int main()
{
int pid, stat, r;
int pids[10];
int i, j;
for (i=0; i<10; i++) {
pid = fork();
if (pid < 0) {
perror("fork err.");
}
else if (pid == 0) {
heavy_function();
_exit(0);
}
else {
pids[i] = pid;
}
}
for (i=0; i<10; i++) {
waitpid(pids[i], &stat, 0);
fprintf(stdout, "p:%d, c=%d\n", i, pids[i]);
}
return 0;
}
using System;
using System.Linq;
using System.Collections.Generic;
namespace Project
{
class Program
{
static int heavy_function()
{
int n = random(5);
System.Threading.Thread.Sleep(n);
return n;
}
static void Main()
{
List<int> pids = new List<int>();
foreach (var i in Enumerable.Range(0, 9)) {
var pid = run_as_background_process(heavy_function);
pids.Add(pid);
}
foreach (var pid in pids) {
var sec = wait(pid);
Console.WriteLine(sec.ToString());
}
}
}
}
#!/bin/bash
# coding: utf-8
# 時間のかかる処理
# 乱数で決めた秒数だけ待機し
# 待機した時間を返す
function heavy_function
{
n=$((RANDOM%5))
sleep $n
return $n
}
# プロセスの実行
pids=
for i in {0..9}
do
heavy_function &
pids="$pids $!"
done
# 実行の待機と結果の印字
for pid in $pids
do
wait $pid
echo $?
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment