#include < unistd.h >
#include < sys/types.h >
#include < stdio.h >
int
main()
{
pid_t pid;
char *argv[3];
extern char **environ;
if((pid = fork())< 0){
perror("fork");
return 1;
} else if(pid == 0){
argv[0]="echo";
argv[1]="Hello, from child";
argv[2]= NULL;
execve("/bin/echo", argv, environ);
_exit(1);
}
write(1, "Hello, from parent\n", 19);
return 0;
}
Month: June 2016
forkによる新しい子プロセスの作成
新しい子プロセスの作成には、forkを使います。
#include < sys/types.h > #include < unistd.h > #includeint main() { pid_t pid; if ((pid = fork()) < 0){ perror("fork"); return 1; } else if (pid == 0){ write(1, "child process\n", 14); _exit(0); } write(1, "parent process\n", 15); return 0; }
ハッシュサーチ
ハッシュサーチは検索は圧倒的に高速です。データをテーブルに格納する際に簡単な式でキーを割り当て、そのキーでダイレクトに飛べる場所にデータを格納しておきます。
#include#include #include #define HASH_SIZE 4096 static char **Str[HASH_SIZE]; static int Strmax[HASH_SIZE]; int strno(char *str) { static char *null=""; char *p,*ptr,*ptrc; int i; unsigned n; if(str==NULL){ ptr=null; } else{ ptr=str; } n=0; for(ptrc=ptr;(*ptrc)!='\0';ptrc++){ n+=(unsigned)(*ptrc); } n%=HASH_SIZE; for(i=0;i
バイナリサーチ
バイナリサーチは条件として、データが昇順にソートされている必要があります。ソートは一般的に検索よりも時間がかかります。
#include < stdio.h >
#include < search.h >
int cmp_func(int *a,int *b)
{
return((*a)-(*b));
}
void main()
{
static int ary[10]={2,4,1,3,5,7,9,6,8,0};
static int target=5;
int *ptr;
qsort(ary,10,sizeof(int),cmp_func);
ptr=(int *)bsearch(&target,ary,10,sizeof(int),cmp=func);
if(ptr!=NULL){
printf("target is ary[%d]\n",ptr-ary);
}
else{
printf("target not found\n");
}
}
線形サーチ
forループで回りながら比較をします。
#include < stdio.h >
void main()
{
static int ary[10]={2,4,1,3,5,7,9,6,8,0};
static int target=5;
int i,no;
no = -1;
for(i=0;i<10;i++){
if(ary[i]==target){
no=i;
break;
}
}
if(no>=0){
printf("target is ary[%d]\n",no);
}
else{
printf("target not found\n");
}
}