1 Replies - 461 Views - Last Post: 29 January 2013 - 08:45 AM Rate Topic: -----

#1 rozkurwiator  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 77
  • Joined: 03-July 12

Semaphore's

Posted 28 January 2013 - 01:59 PM

hi,
I've got a problem with that program. I wan't to make program which writes byte by byte to file, after written every sign is read and written to another file. How have i to organise semaphores? I gave to both semaphores value 0 in the beggining. thanks for help


#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include <unistd.h>
#include<stdlib.h>
struct sembuf buf;
void down(int semid, short semnum)
{
	int sem;
	buf.sem_num=semnum;
	buf.sem_op=1;
	buf.sem_flg=0;
	if((sem=semop(semid, &buf, 1))==-1)
	{
		printf("Blad semop w podnies\n");
		return;
	}
}
void up(int semid, short semnum)
{
	int sem;
	buf.sem_num=semnum;
	buf.sem_op=-1;
	buf.sem_flg=0;
	if((sem=semop(semid, &buf, 1))==-1)
	{
		printf("Blad semop w opusc\n");
		return;
	}
}


////////////////////////

fk=fork();
if(fk>0)
{
	while(buf[i]!='\0')
	{	 	 	
		fp=fopen("plik", "aw");	
		fseek(fp, i, SEEK_SET);		
		fwrite(&buf[i], 1, 1, fp);
		fclose(fp);		
		printf("%d\n", i);						
		i++;	
		up(semid,1);		
		down(semid, 0);		
	}       
	
}               
else if(fk==0)  
{		
	char buf1[100];
	int j=0;	

	while(j<=a)
	{       
		down(semid, 1);
		fp=fopen("plik", "r");	
		fseek(fp, j, SEEK_SET);		
		fread(&buf1[j], 1, 1, fp);
		fclose(fp);								
		fr=fopen("plik1", "aw");			
		fseek(fr, j, SEEK_SET);	
		fwrite(&buf1[j], 1, 1, fr);		
		fclose(fr); 	
		j++;		
		up(semid, 0);		
	
		
	}

This post has been edited by jimblumberg: 28 January 2013 - 02:09 PM
Reason for edit:: Added missing code tags. Please learn to use them properly.


Is This A Good Question/Topic? 0
  • +

Replies To: Semaphore's

#2 vividexstance  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 653
  • View blog
  • Posts: 2,240
  • Joined: 31-December 10

Re: Semaphore's

Posted 29 January 2013 - 08:45 AM

You should check function returns values to see if there was a problem calling that function. Semaphores are used for synchronization between processes, what exactly are you trying to synchronize?

I don't see where you create and initialize any semaphore set. After you've done that, you would typically change the value for the semaphore to let's say 1, and the process does whatever work it needs to. The other process should wait for the semaphores value to equal 0, and therefore it will block until that happens (unless you give the IPC_NOWAIT flag to semop()).

The process that changed the semaphore value to 1 should change it back to 0 once it has completed the work it needed to perform. That way, the process thats blocked waiting for the semaphore value to equal 0 will now execute.

This post has been edited by vividexstance: 29 January 2013 - 08:46 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1