2017-09-14 7 views
3

は、私は、ユーザーが入力したキーを押すまで、私のようなものと思っています実行を継続する機能が必要に押されて:機能の実行は

do{ 
    function(); 
} while(getchar() != "\n"); 

が、私はよく分からない場合は、そのウォン」プログラムが関数を実行する前にユーザーが何かを入力するのを待たせてしまいます。残念なことに、いろいろな理由から、私はそれを書いてすぐにテストすることはできません。これは使えますか?より良い方法がありますか?

+0

入力が押されるまで、反復的に 'function'を呼び出すことができます – krpra

+0

いいえ、動作しません。各反復の入力を待機します。 Cにはこれを実現するための標準機能がありません。 –

+4

最初に '' \ n "' - > ''\ n" ' – BLUEPIXY

答えて

0

同じことを行うには、スレッドプログラムを使用します。 ここでは、メインスレッドの入力を処理し、キーが押されるまで独自のスレッドで実行する別の関数のループで関数を呼び出しています。

ここでは、同期を処理するためにmutexロックを使用しています。 プログラム名がTest.cであると仮定して、qoutesなしで-pthreadフラグ "gcc Test.c -o test -pthread"でコンパイルします。 私はあなたがUbuntuを使用していると仮定しています。

#include<stdio.h> 
#include<pthread.h> 
#include<unistd.h> 
pthread_mutex_t tlock=PTHREAD_MUTEX_INITIALIZER; 
pthread_t tid; 
int keypressed=0; 
void function() 
{ 
    printf("\nInside function"); 
} 
void *threadFun(void *arg) 
{ 
    int condition=1; 
    while(condition) 
    { 
     function(); 
     pthread_mutex_lock(&tlock); 
     if(keypressed==1)//Checking whether Enter input has occurred in main thread. 
      condition=0; 
     pthread_mutex_unlock(&tlock); 
    } 
} 
int main() 
{ 
    char ch; 
    pthread_create(&tid,NULL,&threadFun,NULL);//start threadFun in new thread 
    scanf("%c",&ch); 
    if(ch=='\n') 
    { 
     pthread_mutex_lock(&tlock); 
     keypressed=1;//Setting this will cause the loop in threadFun to break 
     pthread_mutex_unlock(&tlock); 
    } 
    pthread_join(tid,NULL);//Wait for the threadFun to complete execution 
    return 0; 
} 

他の文字を入力する場合は、scanf()を実行してループをチェックする必要があります。