I am using the below app when ever I press cpu`` power on button my application as to pause for few min like 5 min for that I used below app.the problem is I used sleep(300000) for stoping few min but the operation is not performing whenever I press power button please let me know if any on
#include <windows.h>
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#define SHUTDOWN_TEST
FILE *fp;
BOOL CtrlHandler( DWORD fdwCtrlType )
{
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
switch( fdwCtrlType )
{
// Handle the CTRL-C signal.
case CTRL_C_EVENT:
printf( "Ctrl-C event\n\n" );
Beep( 750, 300 );
return( TRUE );
// CTRL-CLOSE: confirm that the user wants to exit.
case CTRL_CLOSE_EVENT:
Beep( 600, 200 );
printf( "Ctrl-Close event\n\n" );
return( TRUE );
// Pass other signals to the next handler.
case CTRL_BREAK_EVENT:
Beep( 900, 200 );
printf( "Ctrl-Break event\n\n" );
return FALSE;
case CTRL_LOGOFF_EVENT:
Beep( 1000, 200 );
printf( "Ctrl-Logoff event\n\n" );
return FALSE;
case CTRL_SHUTDOWN_EVENT:
printf( "Ctrl-Shutdown event\n\n" );
while(1)
{
Sleep(300000);
}
Beep( 750, 500 );
return FALSE;
default:
return FALSE;
}
}
int main( void )
{
fp = (fopen("C:\\shutdown.txt","w"));
#ifdef SHUTDOWN_TEST
if( SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE ) )
{
printf( "\nThe Control Handler is installed.\n" );
printf( "\n -- Now try pressing Ctrl+C or Ctrl+Break, or" );
printf( "\n try logging off or closing the console...\n" );
printf( "\n(...waiting in a loop for events...)\n\n" );
while( 1 ){
printf("I am running\n");
Sleep(3000) ;
}
}
else
{
printf( "\nERROR: Could not set control handler");
return 1;
}
fclose(fp);
#else
if (pid = fork())
{
if( SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE ) )
{
printf( "\nThe Control Handler is installed.\n" );
printf( "\n -- Now try pressing Ctrl+C or Ctrl+Break, or" );
printf( "\n try logging off or closing the console...\n" );
printf( "\n(...waiting in a loop for events...)\n\n" );
while( 1 ){
// printf("I am running\n");
// Sleep(3000) ;
}
}
}
else
{
}
#endif
return 0;
}
Blocking the System shutdown can not be done inside such a handler. Since Windows Vista there is a new API.
Use ShutdownBlockReasonCreate
You can use GetConsoleWindow to get the requested window handle.
Read this link to see the changes since Vista.
Related
I recently wanted to get my hands dirty with understanding how to fork/exec a child process and redirecting stdin, stdout, and stderr thereof, by way of which I wrote my own popen() and pclose()-like functions named my_popen() and my_pclose(), inspired by Apple's open-source implementation of popen() and pclose().
By human-inspection -- e.g. running ps in a different terminal to look for the expected child process -- the popen() seems to work in that the expected child process shows up.
Question: Why does my_pclose() return immediately with errno == 10 (ECHILD) if I call it immediately after my_popen()? My expectation was that my_pclose() would wait until the child process ended.
Question: Given the above, why does my_pclose() return as expected -- after the child process gracefully ends -- if I insert a delay between my_popen() and my_pclose()?
Question: What correction(s) is/are needed for my_pclose() to reliably return only after the child process has ended, without the need of any delays or other contrivances?
MCVE below.
Some context: I wanted my_popen() to allow the user to 1) write to the child process' stdin, 2) read the child process' stdout, 3) read the child process' stderr, 4) know the child process' pid_t, 5) run in environments where fork/exec'ed processes might be either child or grandchild processes, and be able to kill the grandchild process in case of the latter (hence the setpgid()).
// main.c
#include <errno.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
typedef int Pipe[2];
typedef enum PipeEnd {
READ_END = 0,
WRITE_END = 1
} PipeEnd;
#define INVALID_FD (-1)
#define INVALID_PID (0)
typedef struct my_popen_t {
bool success; ///< true if the child process was spawned.
Pipe stdin; ///< parent -> stdin[WRITE_END] -> child's stdin
Pipe stdout; ///< child -> stdout[WRITE_END] -> parent reads stdout[READ_END]
Pipe stderr; ///< child -> stderr[WRITE_END] -> parent reads stderr[READ_END]
pid_t pid; ///< child process' pid
} my_popen_t;
/** dup2( p[pe] ) then close and invalidate both ends of p */
static void dupFd( Pipe p, const PipeEnd pe, const int fd ) {
dup2( p[pe], fd);
close( p[READ_END] );
close( p[WRITE_END] );
p[READ_END] = INVALID_FD;
p[WRITE_END] = INVALID_FD;
}
/**
* Redirect a parent-accessible pipe to the child's stdin, and redirect the
* child's stdout and stderr to parent-accesible pipes.
*/
my_popen_t my_popen( const char* cmd ) {
my_popen_t r = { false,
{ INVALID_FD, INVALID_FD },
{ INVALID_FD, INVALID_FD },
{ INVALID_FD, INVALID_FD },
INVALID_PID };
if ( -1 == pipe( r.stdin ) ) { goto end; }
if ( -1 == pipe( r.stdout ) ) { goto end; }
if ( -1 == pipe( r.stderr ) ) { goto end; }
switch ( (r.pid = fork()) ) {
case -1: // Error
goto end;
case 0: // Child process
dupFd( r.stdin, READ_END, STDIN_FILENO );
dupFd( r.stdout, WRITE_END, STDOUT_FILENO );
dupFd( r.stderr, WRITE_END, STDERR_FILENO );
setpgid( getpid(), getpid() );
{
char* argv[] = { (char*)"sh", (char*)"-c", (char*)cmd, NULL };
// #todo Research why - as has been pointed out - _exit() should be
// used here, not exit().
if ( -1 == execvp( argv[0], argv ) ) { exit(0); }
}
}
// Parent process
close( r.stdin[READ_END] );
r.stdin[READ_END] = INVALID_FD;
close( r.stdout[WRITE_END] );
r.stdout[WRITE_END] = INVALID_FD;
close( r.stderr[WRITE_END] );
r.stderr[WRITE_END] = INVALID_FD;
r.success = true;
end:
if ( ! r.success ) {
if ( INVALID_FD != r.stdin[READ_END] ) { close( r.stdin[READ_END] ); }
if ( INVALID_FD != r.stdin[WRITE_END] ) { close( r.stdin[WRITE_END] ); }
if ( INVALID_FD != r.stdout[READ_END] ) { close( r.stdout[READ_END] ); }
if ( INVALID_FD != r.stdout[WRITE_END] ) { close( r.stdout[WRITE_END] ); }
if ( INVALID_FD != r.stderr[READ_END] ) { close( r.stderr[READ_END] ); }
if ( INVALID_FD != r.stderr[WRITE_END] ) { close( r.stderr[WRITE_END] ); }
r.stdin[READ_END] = r.stdin[WRITE_END] =
r.stdout[READ_END] = r.stdout[WRITE_END] =
r.stderr[READ_END] = r.stderr[WRITE_END] = INVALID_FD;
}
return r;
}
int my_pclose( my_popen_t* p ) {
if ( ! p ) { return -1; }
if ( ! p->success ) { return -1; }
if ( INVALID_PID == p->pid ) { return -1; }
{
pid_t pid = INVALID_PID;
int wstatus;
do {
pid = waitpid( -1 * (p->pid), &wstatus, 0 );
} while ( -1 == pid && EINTR == errno );
return ( -1 == pid ? pid : wstatus );
}
}
int main( int argc, char* argv[] ) {
my_popen_t p = my_popen( "sleep 3" );
//sleep( 1 ); // Uncomment this line for my_pclose() success.
int res = my_pclose( &p );
printf( "res: %d, errno: %d (%s)\n", res, errno, strerror( errno ) );
return 0;
}
Execution with undesired failure:
$ gcc --version && gcc -g ./main.c && ./a.out
gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
res: -1, errno: 10 (No child processes)
References: 1, 2, 3
Update:
This link made me wonder whether adding setpgid( pid, 0 ) in the parent-process after fork()ing was relevant. It does appear to work in that after having made the addition, calling my_pclose() immediately after my_popen() does appear to wait until the process has completed.
Honestly, I don't quite understand why this made a difference; I'd be grateful if a knowledgeable community member could offer insight.
my_popen_t my_popen( const char* cmd ) {
my_popen_t r = { false,
{ INVALID_FD, INVALID_FD },
{ INVALID_FD, INVALID_FD },
{ INVALID_FD, INVALID_FD },
INVALID_PID };
if ( -1 == pipe( r.stdin ) ) { goto end; }
if ( -1 == pipe( r.stdout ) ) { goto end; }
if ( -1 == pipe( r.stderr ) ) { goto end; }
switch ( (r.pid = fork()) ) {
case -1: // Error
goto end;
case 0: // Child process
dupFd( r.stdin, READ_END, STDIN_FILENO );
dupFd( r.stdout, WRITE_END, STDOUT_FILENO );
dupFd( r.stderr, WRITE_END, STDERR_FILENO );
//setpgid( getpid(), getpid() ); // This looks unnecessary
{
char* argv[] = { (char*)"sh", (char*)"-c", (char*)cmd, NULL };
// #todo Research why - as has been pointed out - _exit() should be
// used here, not exit().
if ( -1 == execvp( argv[0], argv ) ) { exit(0); }
}
}
// Parent process
setpgid( r.pid, 0 ); // This is the relevant change
close( r.stdin[READ_END] );
r.stdin[READ_END] = INVALID_FD;
close( r.stdout[WRITE_END] );
r.stdout[WRITE_END] = INVALID_FD;
close( r.stderr[WRITE_END] );
r.stderr[WRITE_END] = INVALID_FD;
r.success = true;
end:
if ( ! r.success ) {
if ( INVALID_FD != r.stdin[READ_END] ) { close( r.stdin[READ_END] ); }
if ( INVALID_FD != r.stdin[WRITE_END] ) { close( r.stdin[WRITE_END] ); }
if ( INVALID_FD != r.stdout[READ_END] ) { close( r.stdout[READ_END] ); }
if ( INVALID_FD != r.stdout[WRITE_END] ) { close( r.stdout[WRITE_END] ); }
if ( INVALID_FD != r.stderr[READ_END] ) { close( r.stderr[READ_END] ); }
if ( INVALID_FD != r.stderr[WRITE_END] ) { close( r.stderr[WRITE_END] ); }
r.stdin[READ_END] = r.stdin[WRITE_END] =
r.stdout[READ_END] = r.stdout[WRITE_END] =
r.stderr[READ_END] = r.stderr[WRITE_END] = INVALID_FD;
}
return r;
}
The problem with your my_pclose() is that you are trying to perform a process-group wait instead of waiting for the specific child process. This:
pid = waitpid( -1 * (p->pid), &wstatus, 0 );
attempts to wait for a child belonging to process group p->pid, but that is extremely unlikely to work without the setpgid() call you later added. The forked child will initially be in the same process group as its parent, and that group's process group number almost certainly will differ from the child's process number.
Moreover, it's unclear why you are trying to wait on the process group in the first place. You know the specific process you want to wait for, and it would be incorrect for my_pclose() to collect a different one instead, regardless of whether it belongs to the same process group. You should wait for that specific process:
pid = waitpid(p->pid, &wstatus, 0 );
That will work either with or without the setpgid() call, but almost certainly you should omit that call in a general-purpose function such as this.
I'm trying to bolster my understanding of things related to fork, exec, dup, and redirecting stdin/stdout/stderr by writing the following popen-type function:
// main.c
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define INVALID_FD (-1)
typedef enum PipeEnd {
READ_END = 0,
WRITE_END = 1
} PipeEnd;
typedef int Pipe[2];
/** Encapsulates information about a created child process. */
typedef struct popen2_t {
bool success; ///< true if the child process was spawned.
Pipe stdin; ///< parent -> stdin[WRITE_END] -> child's stdin
Pipe stdout; ///< child -> stdout[WRITE_END] -> parent reads stdout[READ_END]
Pipe stderr; ///< child -> stderr[WRITE_END] -> parent reads stderr[READ_END]
pid_t pid; ///< child process' pid
} popen2_t;
/** dup2( p[pe] ) then close and invalidate both ends of p */
static void dupFd( Pipe p, const PipeEnd pe, const int fd ) {
dup2( p[pe], fd);
close( p[READ_END] );
close( p[WRITE_END] );
p[READ_END] = INVALID_FD;
p[WRITE_END] = INVALID_FD;
}
popen2_t popen2( const char* cmd ) {
popen2_t r = { false, { INVALID_FD, INVALID_FD } };
if ( -1 == pipe( r.stdin ) ) { goto end; }
if ( -1 == pipe( r.stdout ) ) { goto end; }
if ( -1 == pipe( r.stderr ) ) { goto end; }
switch ( (r.pid = fork()) ) {
case -1: // Error
goto end;
case 0: // Child process
dupFd( r.stdin, READ_END, STDIN_FILENO );
dupFd( r.stdout, WRITE_END, STDOUT_FILENO );
dupFd( r.stderr, WRITE_END, STDERR_FILENO );
{
char* argv[] = { "sh", "-c", (char*)cmd, NULL };
if ( -1 == execvp( argv[0], argv ) ) { exit(0); }
}
}
// Parent process
close( r.stdin[READ_END] );
r.stdin[READ_END] = INVALID_FD;
close( r.stdout[WRITE_END] );
r.stdout[WRITE_END] = INVALID_FD;
close( r.stderr[WRITE_END] );
r.stderr[WRITE_END] = INVALID_FD;
r.success = true;
end:
if ( ! r.success ) {
if ( INVALID_FD != r.stdin[READ_END] ) { close( r.stdin[READ_END] ); }
if ( INVALID_FD != r.stdin[WRITE_END] ) { close( r.stdin[WRITE_END] ); }
if ( INVALID_FD != r.stdout[READ_END] ) { close( r.stdout[READ_END] ); }
if ( INVALID_FD != r.stdout[WRITE_END] ) { close( r.stdout[WRITE_END] ); }
if ( INVALID_FD != r.stderr[READ_END] ) { close( r.stderr[READ_END] ); }
if ( INVALID_FD != r.stderr[WRITE_END] ) { close( r.stderr[WRITE_END] ); }
r.stdin[READ_END] = r.stdin[WRITE_END] =
r.stdout[READ_END] = r.stdout[WRITE_END] =
r.stderr[READ_END] = r.stderr[WRITE_END] = INVALID_FD;
}
return r;
}
int main( int argc, char* argv[] ) {
popen2_t p = popen2( "./child.out" );
{
int status = 0;
sleep( 2 );
{
char buf[1024] = { '\0' };
read( p.stdout[READ_END], buf, sizeof buf );
printf( "%s", buf );
}
//pid_t wpid = waitpid( p.pid, &status, 0 );
//return wpid == p.pid && WIFEXITED( status ) ? WEXITSTATUS( status ) : -1;
}
}
// child.c
#include <stdio.h>
#include <unistd.h>
int main( int argc, char* argv[] ) {
printf( "%s:%d\n", __FILE__, __LINE__ );
sleep( 1 );
printf( "%s:%d\n", __FILE__, __LINE__ );
sleep( 1 );
printf( "%s:%d\n", __FILE__, __LINE__ );
sleep( 1 );
printf( "%s:%d\n", __FILE__, __LINE__ );
sleep( 1 );
return 0;
}
Compilation and execution:
$ gcc --version && gcc -g ./child.c -o ./child.out && gcc -g ./main.c && ./a.out
gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
./child.c:6
./child.c:8
./child.c:10
./child.c:12
$
My question is about the read() - I don't quite grok why does the read() is seemingly block until the child process has completed (thereby closing its end of the pipe)?
Is it coincidence? You can see I've tried to "make" the main process do its read in the middle of the child process' execution with the sleep( 2 ) statement.
In total, the child process dumps 50 chars to its (redirected) stdout. Isn't it possible that the main process might do its read() in the middle of the child's execution and read only N of 50 of those chars, and that therefore the main process' printf() wouldn't print all four lines from the child process in its entirety?
(Functionality-wise, everything is fine - my question is to better my understanding of read())
By default, stdout is fully buffered when it's not writing to a terminal. So nothing is being written to the pipe by your printf() calls in the child until the buffer is flushed. This will happen when the buffer fills (probably 1K or 4K bytes) or the process exits.
You can flush the buffer immediately with fflush(stdout);. Add that after each of your printf() calls and you'll be able to read them in the parent without waiting for the process to exit.
I need to block a connection from the Server side, based on users who type up/down/left/right arrow on the Client side.
I tried one of the following, but it does not work:
strcmp( userName, "^[[A" ) == 0
I created a socket server which checks a connection for an valid nickname, but when the client types one of the arrows:
up arrow = ^[[A
down arrow = ^[[B
left arrow = ^[[D
right arrow = ^[[C
On the server side is just ignored and it does not close the client.
Here is a program which illustrate the problem:
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8888
#define MSGLEN 256
#define MAXNAMELENGTH 25
int server_socket = 0;
int client_socket = 0;
struct sockaddr_in address;
void create_sckt ( void );
void bind_sckt ( const size_t server_len );
void listen_sckt ( void );
void accept_sckt ( size_t server_len );
ssize_t recv_sckt ( char *const userName );
void send_msg ( const int userID, const char *const userName );
int main( void )
{
size_t server_len = sizeof( address );
char userName[ MSGLEN + 1 ] = { 0 };
const char *const wrong_name = "[+]Please type a Valide Name and come back.\n";
create_sckt ();
bind_sckt ( server_len );
listen_sckt ();
printf( "Starting Server...\n" );
while ( 1 )
{
accept_sckt( server_len );
memset( userName, '\0', sizeof(userName ) );
recv_sckt( userName );
userName[ strcspn( userName, "\n" ) ] = 0;
if ( strcmp( userName, "^[[A" ) == 0 && strlen( userName ) > MAXNAMELENGTH )
{
send_msg ( client_socket, wrong_name );
close( client_socket );
break;
}else
{
char welcome_msg[1024] = { 0 };
sprintf( welcome_msg, " Welcome %s\n", userName );
send_msg ( client_socket, welcome_msg );
}
}
close( server_socket );
}
void create_sckt ( void )
{
server_socket = socket( AF_INET, SOCK_STREAM, 0 );
if ( server_socket == -1 )
{
printf("socket() failed\n");
fprintf(stderr, "%s %d\n", strerror(errno), errno);
exit ( EXIT_FAILURE );
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
}
void listen_sckt ( void )
{
int ret = listen( server_socket, 3 );
if ( ret == -1 )
{
printf ( "listen() failed\n" );
fprintf( stderr, "%s %d\n", strerror( errno ), errno );
exit ( EXIT_FAILURE );
}
}
void bind_sckt ( const size_t server_len )
{
int ret = bind( server_socket, ( struct sockaddr* )&address, ( socklen_t )server_len );
if ( ret == -1 )
{
printf ( "bind() failed\n" );
fprintf( stderr, "%s %d\n", strerror( errno ), errno);
exit ( EXIT_FAILURE );
}
}
void accept_sckt ( size_t server_len )
{
client_socket = accept( server_socket, (struct sockaddr *)&address, (socklen_t*)&server_len );
if ( client_socket == -1 )
{
printf ( "accept() failed\n" );
fprintf( stderr, "%s %d\n", strerror(errno), errno );
exit ( EXIT_FAILURE );
}
}
void send_msg ( const int userID, const char *const userName )
{
ssize_t ret = send( userID , userName , strlen( userName ) , 0 );
if ( ret == -1 )
{
printf ( "recv() failed\n" );
fprintf( stderr, "%s %d\n", strerror( errno ), errno );
exit ( EXIT_FAILURE );
}else
{
printf( "Hello message sent\n" );
}
}
ssize_t recv_sckt ( char *const userName )
{
ssize_t ret = recv( client_socket, userName, MSGLEN, 0);
if ( ret == -1 )
{
printf ( "recv() failed\n" );
fprintf( stderr, "%s %d\n", strerror( errno ), errno );
exit ( EXIT_FAILURE );
}
return ret;
}
How should I block the connection, when on the client side are used one of the arrow keys?
On the client side it prints (welcome ):
Please enter your name: ^[[A
Connect to Server: 192.168.0.103:8888
You are: 192.168.0.103:42074
Welcome
After I tried examples which was provided in the above Answer and also in one comment and did not work. I found a solution to my problem.
GCC seems to allow \e but it is not standard:
error: non-ISO-standard escape sequence, '\e'|
Tryed also with "\x27[A" and still no working.
The only thing which worked in this case is 0x1B:
if ( userName[0] == 0x1B )
Because the first two characters ^[ represent a single escape character. Try comparing to string "\e[A" instead. And change the logical operator from && to ||. You want to fail if it's an arrow or it's too long.
I am trying to make an application which uses AES 256 Encryption. Unfortunately i can't get it work. Maybe i didn't understand the crpytographic logic fully.
So it is working, but as far as i understand the hash contains the password. But if i change the password the output is the same. So it seems that CryptEncrypt ignoes the Hash.
Could someone please help me?
Thanks in advance!
Here is my code:
if ( !CryptAcquireContext( &hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT ) )
{
printf( "\nCryptAcquireContext failed %d", GetLastError() );
return;
}
if ( !CryptImportKey( hProv, ( const LPBYTE )&keyBlob, sizeof( keyBlob ), 0, CRYPT_EXPORTABLE, &hPubKey ) )
{
printf( "\nCryptImportKey failed %d", GetLastError() );
return;
}
if ( !CryptCreateHash( hProv, CALG_SHA_256, 0, 0, &hHash ) )
{
printf( "Error %x during CryptCreateHash!\n", GetLastError() );
return;
}
if ( !CryptHashData( hHash, ( PBYTE )wszPassword, cbPassword, 0 ) )
{
printf( "Error %x during CryptHashData!\n", GetLastError() );
return;
}
//if ( !CryptDeriveKey( hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey ) )//hKey
//{
// printf( "Error %x during CryptDeriveKey!\n", GetLastError() );
// return;
//}
if ( !CryptSetKeyParam( hPubKey, KP_IV, ivData, 0 ) )
{
printf( "\nCryptSetKeyParam failed %d", GetLastError() );
return;
}
DWORD size = ( DWORD )strlen( StringToEncrypt ) / sizeof( char );
//printf( "\nLength of string to encrypt = %d\n\n", size );
if ( !CryptEncrypt( hPubKey, hHash, TRUE, 0, ( LPBYTE )StringToEncrypt, &size, ( size / 16 + 1 ) * 16 ) )
{
printf( "\nCryptEncrypt failed %d", GetLastError() );
int a = GetLastError();
switch ( a )
{
case NTE_BAD_HASH_STATE: printf( "NTE_BAD_HASH_STATE" ); break;
case NTE_BAD_HASH: printf( "NTE_BAD_HASH" ); break;
}
return;
}
The "password" - usually known as the key - is in hPubKey. The hHash is for generating a hash at the same time as the encryption is done. Look here for more information.
I'm trying to cancel a thread that way :
pthread_cancel(threads[id]);
And I release the mutex before cancelling the thread.
And after that I need to restart it because it was causing a DeadLock
usleep(1);
pthread_create(&threads[id], NULL, aFunction, &id );
usleep(1);
pthread_join(threads[id], NULL);
usleep(1);
I tried to remove pthread_join, but no luck.
This is a big part of the code :
#define LEFT(i) i
#define RIGHT(i) (i+1) % N
#define CreateSemaphore(s,v) sem_init( &s, 0, v)
#define WaitSemaphore(s) sem_wait( &s )
#define SignalSemaphore(s) sem_post( &s )
#define ReleaseSemaphore(s) sem_destroy( &s )
void restart(int id) {
release(id, LEFT(id));
int res;
if (allocated[id][RIGHT(id)] == 1) {
release(id, RIGHT(id));
}
res = pthread_cancel(threads[id]);
if (res != 0) {
perror("Thread cancelation failed");
exit(EXIT_FAILURE);
}
usleep(1);
res = pthread_create(&threads[id], NULL, aFunction, &id );
usleep(1);
if (res != 0 ) {
fprintf( stderr, "Error creating the thread %d \n", id );
exit( 1 );
}
printf("Waiting for thread to finish...\n");
res = pthread_join(threads[id], NULL);
if (res != 0) {
perror("Thread join failed");
exit(EXIT_FAILURE);
} else
printf("Passed join...\n");
usleep(1);
}
void * aFunction( void *i )
{
int value = *((int *)i);
while ( 1 ){
think( value );
take( value );
eat( value );
drop( value );
}
pthread_exit( NULL );
}
void take( int i ) {
request(i, LEFT(i));
WaitSemaphore( fork[LEFT(i)] );
allocation(i, LEFT(i));
usleep(100);
request(i, RIGHT(i));
WaitSemaphore( fork[RIGHT(i)] );
allocation(i, RIGHT(i));
usleep(100);
}
void drop( int i )
{
SignalSemaphore( forks[LEFT(i)] );
release(i, LEFT(i));
usleep(100);
SignalSemaphore( forks[RIGHT(i)] );
release(i, RIGHT(i));
usleep(100);
}
void release(int id, int f) {
WaitSemaphore(mutex[f]);
beingUsed[id][f] = 0;
currentAvail[f] = 1;
SignalSemaphore(mutex[f]);
}
did you try with pthread_exit(1) inside the thread code? This is other way to finish the running thread when it finishes it work.