0 / 0 / 0
Регистрация: 27.01.2014
Сообщений: 8
1

Работа с процессами и каналами в windows

28.01.2014, 20:55. Показов 1267. Ответов 0
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Была задача. Считать матрицы, послать их дочернему процессу, где найдется матрица из ср. арифметического элементов других матриц, результирующая матрица должна вывестись в родительском процессе.
Не понимаю в чем проблема, но как мне кажется не правильно посылаю через канал в дочерний процесс массив указателей на матрицы. Программа ломается дойдя до строчки ReadFile. Сам алгоритм вычисления ср. арифм. матриц работает нормально (в одном файле без разделения на процессы).
Подскажите ошибку.

Родительский файл:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <Windows.h>
#include <iostream>
#include <tchar.h>
#include <stdlib.h>
using namespace std;
 
int main()
{
    DWORD bytes;
    int count, n;
 
    cout << "Size of matrix(N x N): ";
    cin >> n;
    cout << "Enter number of matrix: ";
    cin >> count;
 
    int **Obj = (int **)malloc(sizeof(int)*count);
    double *Result = (double *)malloc(sizeof(double)*n*n);
 
    //Create matrix
    for(int a = 0; a < count; a ++)
    {
        int *Matrix = new int[n*n];
        cout << "Enter " << a+1 << " matrix " << n << " x " << n <<":" << endl;
        for(int i = 0; i < n; i ++)
        {
            for(int j = 0; j < n; j ++)
            {
                cin >> *(Matrix+i*n+j);
            }
        }
        Obj[a] = Matrix;
    }
 
    for(int i = 0; i < n; i ++)
        for(int j = 0; j < n; j ++)
            *(Result+i*n+j) = 0;
 
    while(1)
    {
    //Create Process and Pipes
    LPTSTR szCmd = _tcsdup(TEXT("Child.exe"));
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    SECURITY_ATTRIBUTES sa;
    HANDLE hStdin, hStdout, write, read;
 
    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags = STARTF_USESTDHANDLES;
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;
 
    if(!CreatePipe(&read, &hStdout, &sa, 0))
        cout << "Creating read pipe fail" << endl;
    if(!CreatePipe(&hStdin, &write, &sa, 0))
        cout << "Creating write pipe fail" << endl;
 
    if(!SetHandleInformation(write, HANDLE_FLAG_INHERIT, 0))
        cout << "SetHandleInformation fail" << endl;
    if(!SetHandleInformation(read, HANDLE_FLAG_INHERIT, 0))
        cout << "SetHandleInformation fail" << endl;
 
    si.hStdInput = hStdin;
    si.hStdOutput = hStdout;
 
    if(!CreateProcess(NULL, szCmd, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
        cout << "Process fail" << endl;
 
    //Write and Read
    WriteFile(write, &count, sizeof(int), &bytes, 0);
    WriteFile(write, &n, sizeof(int), &bytes, 0);
    WriteFile(write, *Obj, sizeof(int)*count, &bytes, 0);
    CloseHandle(write);
    WaitForSingleObject(pi.hProcess, INFINITE);
    ReadFile(read, Result, sizeof(double)*(n*n), &bytes, 0);
 
    //Show result Matrix
    for(int i = 0; i < n; i ++)
    {
        for(int j = 0; j < n; j ++)
        {
            cout << *(Result+i*n+j) << " ";
        }
        cout << endl;
    }
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
 
    system("pause");
    return 0;
    }
}
Дочерний файл (Child.ccp)
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <Windows.h>
#include <iostream>
using namespace std;
 
int main()
{
    int count;
    int n;
    HANDLE hStdin, hStdout;
    hStdin = GetStdHandle(STD_INPUT_HANDLE);
    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD bytes;
 
    ReadFile(hStdin, &count, sizeof(int), &bytes, 0);
    ReadFile(hStdin, &n, sizeof(int), &bytes, 0);
    int **Obj = (int **)malloc(sizeof(int)*count);
    ReadFile(hStdin, *Obj, sizeof(int)*count, &bytes, 0);
    double *Result = (double *)malloc(sizeof(double)*n*n);
 
    //Average Matrix
    for(int i = 0; i < n; i ++)
        for(int j = 0; j < n; j ++)
            *(Result+i*n+j) = 0;
 
    for(int i = 0; i < n; i ++)
    {
        for(int j = 0; j < n; j ++)
        {
            for(int a = 0; a < count; a ++)
            {
                int *Matrix = Obj[a];
                *(Result+i*n+j) += *(Matrix+i*n+j);
            }
            *(Result+i*n+j) /= n;
        }
    }
 
    WriteFile(hStdout, Result, sizeof(double)*(n*n), &bytes, 0);
    return 0;
}
Добавлено через 22 часа 51 минуту
Все, разобрался с решением проблемы.
Нужно было в канал посылать указатели на каждую строку матрицы) Так как сторонняя программа выделяет другие ячейки памяти под матрицы
Может быть кому-то пригодиться:

Parent
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <Windows.h>
#include <iostream>
#include <tchar.h>
#include <stdlib.h>
using namespace std;
 
int main()
{
    DWORD bytes;
    int count, n;
 
    cout << "Size of matrix(N x N): ";
    cin >> n;
    cout << "Enter number of matrix: ";
    cin >> count;
 
    //Create matrix
    int ***Matrix = new int**[count];
    for(int a = 0; a < count; a ++)
    {
        Matrix[a]= new int*[n];
        cout << "Enter " << a+1 << " matrix " << n << " x " << n <<":" << endl;
        for(int i = 0; i < n; i ++)
        {
            Matrix[a][i] = new int[n];
            for(int j = 0; j < n; j ++)
                cin >> Matrix[a][i][j];
        }
    }
 
    //Memory for Result matrix
    double **Result = new double*[n*n];
    for(int i = 0; i < n; i ++)
        Result[i] = new double[n];
 
    while(1)
    {
    //Create Process and Pipes
    LPTSTR szCmd = _tcsdup(TEXT("Child.exe"));
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    SECURITY_ATTRIBUTES sa;
    HANDLE hStdin, hStdout, write, read;
 
    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags = STARTF_USESTDHANDLES;
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;
 
    if(!CreatePipe(&read, &hStdout, &sa, 0))
        cout << "Creating read pipe fail" << endl;
    if(!CreatePipe(&hStdin, &write, &sa, 0))
        cout << "Creating write pipe fail" << endl;
 
    if(!SetHandleInformation(write, HANDLE_FLAG_INHERIT, 0))
        cout << "SetHandleInformation fail" << endl;
    if(!SetHandleInformation(read, HANDLE_FLAG_INHERIT, 0))
        cout << "SetHandleInformation fail" << endl;
 
    si.hStdInput = hStdin;
    si.hStdOutput = hStdout;
 
    if(!CreateProcess(NULL, szCmd, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
        cout << "Process fail" << endl;
 
    //Write into Child process
    WriteFile(write, &count, sizeof(int), &bytes, 0);
    WriteFile(write, &n, sizeof(int), &bytes, 0);
    for(int i = 0; i < count; i ++)
    {
        for(int j = 0; j < n; j ++)
            WriteFile(write, Matrix[i][j], sizeof(int)*(count*n), &bytes, 0);
    }
    CloseHandle(write);
 
    //Read result matrix from Child
    WaitForSingleObject(pi.hProcess, INFINITE);
    for(int i = 0; i < n; i++)
        ReadFile(read, Result[i], sizeof(double)*(n), &bytes, 0);
 
    //Show result Matrix
    cout << endl << "result: " << endl;
    for(int i = 0; i < n; i ++)
    {
        for(int j = 0; j < n; j ++)
        {
            cout << Result[i][j] << "   ";
        }
        cout << endl;
    }
 
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
 
    system("pause");
    return 0;
    }
}
Child
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <Windows.h>
#include <iostream>
using namespace std;
 
int main()
{
    int count;
    int n;
    HANDLE hStdin, hStdout;
    hStdin = GetStdHandle(STD_INPUT_HANDLE);
    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD bytes;
 
    ReadFile(hStdin, &count, sizeof(int), &bytes, 0);
    ReadFile(hStdin, &n, sizeof(int), &bytes, 0);
 
    //Memory for Read Matrix
    int ***Matrix = new int**[count];
    for(int i = 0; i < count; i++)
    {
        Matrix[i] = new int*[n];
        for(int j = 0; j < n; j++)
            Matrix[i][j] = new int[n];
    }
 
    //Memory for Result Matrix, 0
    double **Result = new double*[n];
    for(int k = 0; k < n; k++)
    {
        Result[k] = new double[n];
        for(int j = 0; j < n; j++)
            Result[k][j] = 0;
    }
 
    //Read from Parent process Matrix
    for(int i = 0; i < count; i ++)
    {
        for(int j = 0; j < n; j ++)
            ReadFile(hStdin, Matrix[i][j], sizeof(int)*(count*n), &bytes, 0);
    }
    
    //Average Matrix
    for(int i = 0; i < n; i ++)
    {
        for(int j = 0; j < n; j ++)
        {
            for(int a = 0; a < count; a ++)
            {
                Result[i][j] += Matrix[a][i][j];
            }
            Result[i][j] /= count;
        }
    }
 
    //Write into Parent
    for(int i = 0; i < n; i ++)
        WriteFile(hStdout, Result[i], sizeof(double)*(n), &bytes, 0);
    return 0;
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
28.01.2014, 20:55
Ответы с готовыми решениями:

Работа с процессами и каналами
Кто подскажет как такое делать и с чего вообще начать разбирать лабораторную? Условие: Исходный...

Работа с процессами
Разработать программу которая читает из одного файла массив A1, а из другого – массив А2. Процесс...

Работа с процессами и потоками
Здравствуйте! Нужна ваша помощь! Если кто знает как делать эти задания, буду очень благодарен. ...

Win32 API Работа с процессами
Господа, здравствуйте! Я новичок в программировании, помогите пожалуйста в программе, не знаю как...

0
28.01.2014, 20:55
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
28.01.2014, 20:55
Помогаю со студенческими работами здесь

Системные вызовы и работа с процессами
Помогите пожалуйста с такой задачей: Родительский процесс считывает стандартной входной поток,...

Системное программирование. Работа с процессами и анонимным каналом
Есть задание .Программа порождает два процесса, один процесс пишет в неименованный канал, другой...

Работа с потоками и процессами windows
Почему выбивает ошибку в строке PInf *Inf ? Нашёл пример в методичке..помогите разобраться ...

Работа с процессами и потоками в Windows
Создать приложение, запускающее пять дочерних потоков. Каждый поток выполняет вывод сообщения об...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru